我试图动态生成Rest响应的输入字段。我无法通过为所有输入字段指定unique Id
或unique name
来设置状态,因为name
和id
值是动态生成的。
这是我的代码:
export default class Rest extends Component {
constructor() {
super();
this.state = {
First_Name: "",
data: [],
}
}
handlesubmit = (e) => {
e.preventDefault();
const {First_Name} = this.state;
console.log(this.state)
}
someFunc = (e) => {
const state = this.state
state[e.target.name] = e.target.value;
this.setState(state);
}
componentDidMount() {
fetch('https://facebook.github.io/react-native/movies.json').then((Response) => Response.json()).
then((findresponse) =>
{
console.log(findresponse.movies)
this.setState({
data: findresponse.movies
})
})
}
render()
{
const {First_Name} = this.state;
return(
<div>
<form onSubmit={this.handlesubmit}>
<table className="tat">
<tr><th>name</th><th>year</th></tr>
{
this.state.data.map((dynamicData) =>
<tr className="trow"> <td> {dynamicData.title}
</td> <td> {dynamicData.releaseYear} </td> <td><Input placeholder="First Name..." value={First_Name} name="First_Name" id={dynamicData.releaseYear} onChange={this.someFunc}/></td>
</tr>
) }
</table>
<button type="Submit">submit</button>
</form>
</div>
)
}
}
The output for the following code
问题是e.target.name
指定了生成的所有输入字段的一个特定名称。因此,如果我设置<input name={dynamicdata.releaseYear} />
,我将如何为动态生成名称的所有输入字段设置状态。
谢谢...
答案 0 :(得分:1)
您正在尝试直接改变您的州:
someFunc = (e) => {
const state = this.state
state[e.target.name] = e.target.value;
this.setState(state);
}
你可以这样做:
someFunc = (e) => {
const newState = JSON.parse(JSON.stringify(this.state));
newState[e.target.name] = e.target.value;
this.setState(newState);
}
更新:
将e.target.name
更改为e.target.id
,以便每个键id
都会存储相应输入字段的值。
someFunc = (e) => {
const newState = JSON.parse(JSON.stringify(this.state));
newState[e.target.id] = e.target.value;
this.setState(newState);
}
答案 1 :(得分:0)
哦,我以前遇到过这个问题。将您的form
更新为
<form onSubmit={(e) => this.handlesubmit(e)}>
<table className="tat">
<tr><th>name</th><th>year</th></tr>
{
this.state.data.map((dynamicData) =>
(<tr className="trow"> <td> {dynamicData.title}
</td> <td> {dynamicData.releaseYear} </td> <td><Input placeholder="First Name..." value={First_Name} name="First_Name" id={dynamicData.releaseYear} onChange={(e) => this.someFunc(e)}/></td>
</tr>)
) }
</table>
<button type="Submit">submit</button>
</form>
将onSubmit
和onChange
功能更改为:
onSubmit={(e) => this.handlesubmit(e)}
和
onChange={(e) => this.someFunc(e)}
分别
问题是因为this
的范围,当您按自己的方式调用onSubmit
或onChange
时,this
是DOM元素而不是React组件,因此{ {1}}无法访问React this
属性。
更新
更改以下功能
state
下一步
onChange={e => this.someFunc(e, dynamicData.releaseYear)} // because dynamicData.releaseYear is the ID
或者如果你想使用名字
someFunc = (e, id) => {
const state = this.state
state[id] = e.target.value; // or state["prefix_"+id] = e.target.value;
this.setState(state);
}