我渲染了一个在按钮单击事件中具有多次选择下拉菜单的组件。
class AppComponent extends React.Component {
constructor(props){
super(props);
this.state = {
numChildren: 0
}
this.onAddChild = this.onAddChild.bind(this);
}
render () {
const children = [];
for (var i = 0; i < this.state.numChildren; i += 1) {
children.push(<ChildComponent key={i} number={i} />);
};
return (
<ParentComponent addChild={this.onAddChild} submit={this.submitData}>
{children}
</ParentComponent>
);
}
submitData(){
console.log("Submit Data button");
}
onAddChild() {
this.setState({
numChildren: this.state.numChildren + 1
});
}
}
ParentComponent在onClick事件上添加子组件。
const ParentComponent = props => (
<div className="card calculator">
<button onClick={props.addChild}>Add Another Child
Component</button>
<button onClick={props.submit}>Submit Data</button>
{props.children}
</div>
);
const ChildComponent = props => < NewComponent />;
class NewComponent extends React.Component{
constructor(props){
super(props);
this.state = {
first: null,
second: null,
third : null,
}
this.changeFirst = this.changeFirst.bind(this);
this.changeSecond = this.changeSecond.bind(this);
this.changeThird = this.changeThird.bind(this);
}
changeFirst(e) {
this.setState({
first : e.target.value
});
}
changeSecond(e) {
this.setState({
second : e.target.value
});
}
changeThird(e) {
this.setState({
third : e.target.value
});
}
render (){
return (
<div>
<select onChange={this.changeFirst}>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
<option value = "Mahindra"> Mahindra</option>
<option value = "Car"> Car</option>
</select>
<select onChange={this.changeSecond}>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
<option value = "Mahindra"> Mahindra</option>
<option value = "Car"> Car</option>
</select>
<select onChange={this.changeThird}>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
<option value = "Mahindra"> Mahindra</option>
<option value = "Car"> Car</option>
</select>
</div>
);
}
}
单击按钮时,NewComponent将呈现为子组件。 我添加了changeFirst,changeSecond和changeThird自定义函数来处理更改事件并设置NewComponent(子组件)的状态。
我想做的是,我想获取每个子组件实例的所有选定值的列表。 任何帮助表示赞赏。
答案 0 :(得分:0)