gpt4 book ai didi

javascript - 安装后以编程方式关注表单元素

转载 作者:行者123 更新时间:2023-11-29 15:28:53 25 4
gpt4 key购买 nike

我有一个表单组件 (FormComponent),我需要在单击同级按钮组件时以编程方式关注它。我曾经能够调用 this.refs.myForm.focus(),它(给定 myForm 作为 FormComponent)被编写为调用 .focus() 在里面的第一个表单字段上。但是,我已经将一些行为重构并抽象到包装 FormComponent 的高阶组件中,所以现在,FormComponent 上的 .focus() 方法被包装器组件拦截。

使用 React 0.14.x(所以我不需要 ReactDOM.findDOMnode() 用于 DOM 组件):

// FormComponent
class FormComponentBase extends React.Component {
focus() {
this.refs.firstField.focus();
}

render() {
return (
<form ...>
<input ref="firstField" />
</form>
);
}
}

// Wraps FormComponent in a wrapper component with abstracted/reusable functionality
const FormComponent = hocWrapper(FormComponent);

// OtherComponent
class OtherComponent extends React.Component {
handleClick(ev) {
// ERROR This doesn't work because the hocWrapper component is intercepting the .focus() call
this.refs.myForm.focus();
}

render() {
return (
<div>
<button onClick={this.handleClick.bind(this)}>Focus</button>
<FormComponent ref="myForm" />
</div>
);
}
}

传递 focus 属性并管理表单的第一个元素是否聚焦在 OtherComponent 中的状态似乎很可笑。我知道您可以使用 defineProperty(或类似的东西)创建 get/set 属性,其中访问实例属性会在后台调用一个方法来生成结果,但是 JS 是否有类似 Ruby 的 missingMethod 或 PHP 的 __call 的东西,我可以在我的 hocWrapper 上定义一个包罗万象的方法,它只是将方法调用传递给包装的组件?在通过 HOC 包装器组件调用其他方法之前,我遇到过这个问题,但我想我只是在 HOC 包装器上定义了一个同名的传递方法(我很确定这是错误的方法)。

最佳答案

您可以使用 ref 回调函数相当轻松地向上传递 ref,而不是向下传递焦点状态。 Here's a fiddle illustrating

class FormComponentBase extends React.Component {
render() {
return (
<form ...>
<input ref={node => this.props.passNode(node)} />
</form>
);
}
}

class OtherComponent extends React.Component {
receiveNode(node) {
if (!this.state.node) this.setState({ node })
}

render() {
return (
<div>
<button onClick={() => this.state.node.focus()}>Focus</button>
<FormComponent passNode={this.receiveNode} />
</div>
);
}
}

更新:一种不向上传递节点的更惯用的方式。 updated fiddle

var FormComponentBase = React.createClass({
render() {
return <input ref={ node =>
node && this.props.shouldFocus && node.focus()
}/>
}
})

var OtherComponent = React.createClass({
getInitialState() {
return { shouldFocus: false }
},

toggleFocus(node) {
// toggle for demonstration
this.setState({ shouldFocus: !this.state.shouldFocus })
},

render: function() {
return (
<div>
<button onClick={() => this.toggleFocus() }>focus</button>
<Child shouldFocus={this.state.shouldFocus} />
</div>
)
}
});

关于javascript - 安装后以编程方式关注表单元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36707854/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com