我是React的新手,我正在努力创建一个包含3个选项的简单动态表单。
我的问题是应根据父选择中选择的选项填写子选项的选项。
这是我的代码:
var MySelect = React.createClass({
getInitialState: function() {
return {
value: 'select'
}
},
change: function(event){
this.setState({value: event.target.value});
},
render: function(){
return(
React.createElement(
'div',
{ },
React.createElement(
'select',
{ id: this.props.id,
onChange: this.change,
value: this.state.value
},
React.createElement("option", null, "Yes"),
React.createElement("option", null, "No"),
this.props.title
),
React.createElement(
'select',
{ id: this.props.id,
onChange: this.change,
value: this.state.value
},
React.createElement("option", null, "Author1"),
React.createElement("option", null, "Author2"),
this.props.title
),
React.createElement(
'select',
{ id: this.props.id,
onChange: this.change,
value: this.state.value
},
React.createElement("option", null, "Book1"),
React.createElement("option", null, "Book2"),
this.props.title
)
));
}
});
因此,如果我们选择是,我们有2位作者,如果我们选择author1 - 我们只能选择book1。
如果我们选择author2,我们只能选择book2而不能选择book1。如果我们选择“否”,我们就无法选择任何作者或书籍。我相信应该有一些州,但我仍然无法从文档中得到重点。
答案 0 :(得分:1)
最好将其分解为组件流,而不是在单个组件中管理复杂状态机中的所有内容。
您可以将Author元素逻辑提取到新组件。如果第一个选择具有“是”,则呈现“作者”组件,否则不呈现。
在作者组件中,您应该管理作为状态选择的作者,并将该状态作为道具传递给Book组件。
在Book组件中,您可以根据在props中收到的作者呈现选择菜单选项。
您还必须在Book组件中使用componentWillReceiveProps
来跟踪更改的道具。
答案 1 :(得分:0)
我将用代码解释。您可以执行以下操作。您可以有3个布尔状态,一个将分配给作者的选择列表,另外两个分配给各个选项值(book1,book2)。根据用户在列表中选择的内容 - 是或否 请考虑以下代码。 是/否选择列表的onchange处理程序
If(event.target.value=="Yes")
{
this.setState({AuthorsSelectable:true,
book1Selectable:true,
book2Selectable:true
});
}
else{
this.setState({AuthorsSelectable:false,
book1Selectable:false,
book2Selectable:false
});
}
现在你将在Author1 / Author2列表的onchange处理程序中
if(event.target.value="Author1"){
this.setState({book1Selectable:true,
book2Selectable:false
});
}
else{
this.setState({
book1Selectable:false.
book2Selectable:true
});
希望这会有所帮助。