我一直在尝试用 React 创建动态。到目前为止,我成功地显示和隐藏了表单,没有出现任何问题。我现在需要从创建的字段中获取值,这导致了一些问题。
这是我到目前为止的代码。
首先,当人们单击按钮时添加我的动态组件:
class MediaInput extends React.Component {
render() {
const linkName = `link-${this.props.index}`;
const contentName = `content-${this.props.index}`;
const linkValue = `this.props.${linkName}`;
const contentValue = `this.props.${contentName}`;
return (
<div>
<ControlLabel>Media (optional)</ControlLabel>
<input
name={ linkName }
value={ linkValue }
className="form-control"
placeholder="Add your media url"
type="text"
/>
<input
name={ contentName }
value={ contentValue }
className="form-control"
placeholder="Add your media content"
type="text"
/>
</div>
);
}
}
首先在渲染部分我有:
const mediaFields = this.state.mediaFields.map((Element, index) => {
return <Element key={ index } index={ index } />
})
这是我的表单中渲染的部分:
<div>
{ mediaFields }
<Button onClick={ () => this.add() }>Add media field</Button>
<Button onClick={ () => this.remove() }>Remove media field</Button>
</div>
我想将这些值保存在父组件的状态中:
mediaUrls: { "link-0": null, "link-1": null, "link-2": null},
mediaContents: { "content-0": null, "content-1": null, "content-2": null}
这有点困惑,但我试图用这个例子来让它工作: Example
我知道第一部分中我设置的 linkValue 和 contentValue 不正确,但我应该如何修复它?
我也知道我仍然需要将 onChange 方法传递给元素,但这是下一步。
更新:
我认为这将是一种更干净的方法,但现在我遇到了不同的问题。
我创建了一个要存储值的数组。我可以在子项中读取它们,但现在如何保存父项中的更改?如何读取父级中子级的索引,以便将其保存在正确的位置?
class MediaInput extends React.Component {
render() {
const linkName = `link${this.props.index}`;
const contentName = `content${this.props.index}`;
return (
<div>
<ControlLabel>Media (optional)</ControlLabel>
<input
onChange={this.props.handleChange}
name={ linkName }
value={ this.props.mediaUrls[this.props.index]}
className="form-control"
placeholder="Add your media url"
type="text"
/>
<input
name={ contentName }
value={ this.props.mediaContents[this.props.index]}
className="form-control"
placeholder="Add your media content"
type="text"
/>
</div>
);
}
}
我的状态:
mediaUrls: [ '', '', ''],
mediaContents: ['', '', ''],
如果我想在每次输入更改时 setState,我的 handleChange 函数应该是什么样子?我想读取索引并根据该索引更改我的数组。
// Handle media fields
handleChange(e){
const mediaUrls = this.state.mediaUrls;
// based on the index, change the value in the array
this.setState({ ??? });
}
最佳答案
要获取父级的索引以进行更新,只需将其传递到回调中即可。
class MediaInput extends React.Component {
// ...
render() {
return (
<div>
<ControlLabel>Media (optional)</ControlLabel>
<input
onChange={(event) => this.props.handleChange(event, this.props.index)} />
When dealing state in React, treat it as immutable.
handleChange(e, index) {
// Shallow copy of array
const mediaUrls = this.state.mediaUrls.slice();
mediaUrls[index] = e.target.value;
this.setState({mediaUrls: mediaUrls});
});
关于javascript - 如何使用react获取动态创建的输入字段的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41295042/