gpt4 book ai didi

javascript - 如何循环表单输入并在 react 中获取值

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

给出以下内容:

constructor () {

super();
this.state = {
inputs : [
{ type: 'email', placeholder: 'Email Address' }
]
};

}

render () {
return {
<div>

{
// Itterates over all inputs in the current state
this.state.inputs.map((item, i) => (
<Input key={i} id={'input-' + i} ref={'input-' + i} type={item.type} placeholder={item.placeholder} />
))
}

<button onClick={this.submit.bind(this)}>submit</button>

</div>

};
}

提交表单后如何获取值?例如

submit () {
// Need to loop over inputs and get values for all of them.
}

最佳答案

我已经根据一些最佳实践重组了代码。如果您对此有任何疑问,请告诉我。

state = {
inputs : [
{ type: 'email', placeholder: 'Email Address', id: 'email' },
{ type: 'text', placeholder: 'Your Name', id: 'name' },
]
},

submit = () => {
// Need to loop over inputs and get values for all of them.
this.state.inputs.map((input) => {
const node = ReactDOM.findDOMNode(this.refs[input.id]);
// do what you want to do with `node`
})
},

renderInput = (input) => {
// element index as key or reference is a horrible idea
// for example if a new input is unshifted it will have the same
// reference or key, which will render the idea of key, reference invalid

return (
<Input
id={input.id}
key={input.id}
ref={input.id}
type={input.type}
placeholder={input.placeholder}
/>
);
}

render () {
return (
<div>
{ this.state.inputs.map(this.renderInput) }
<button onClick={this.handleSubmit}>submit</button>
</div>
);
}

我发现的问题

  1. key 设置为索引是一种反模式。阅读更多 https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318

  2. 在 render 中绑定(bind) this 是一种反模式。使用 es7 类属性来解决这个问题。或者您可以在构造函数中绑定(bind)方法。阅读更多关于绑定(bind)的信息 https://medium.com/@housecor/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56#.uzdapuc4y

解决方案一:

constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}

方案二:

handleSubmit = () => {
// do you stuff
}

关于javascript - 如何循环表单输入并在 react 中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41219033/

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