React子组件数据传递问题:QuestionGrid的value绑定失效求助
修复React组件中单选框选中状态同步问题
我来帮你搞定这个问题~你遇到的核心问题是状态管理的位置不对:当前AnswerGrid自己维护着选中状态,而QuestionGrid想要获取这个选中值时,因为两个组件的状态是独立的,自然没法同步,所以value={this.props.active}就没法正常显示选中结果。
我们需要把状态**提升到父组件QuestionGrid**来统一管理,这样父组件既能控制子组件的选中状态,也能实时拿到选中的值。下面是修改后的完整代码:
修改后的QuestionGrid组件
const QuestionGrid = React.createClass({ // 把选中状态移到父组件管理 getInitialState: function(){ return {active: null}; }, // 定义回调方法,接收子组件传递的选中值 handleAnswerSelect: function(selectedAnswerId) { this.setState({active: selectedAnswerId}); }, render : function(){ var rows = []; var question_id = this.props.question.question_id; this.props.question.list_answer.map(function(answer){ // 传递选中状态和回调给子组件 rows.push( <AnswerGrid key={answer.answer_id} answer={answer} question_id={question_id} active={this.state.active} onSelect={this.handleAnswerSelect} /> ); }.bind(this)); // 注意绑定this,避免map里this指向错误 return ( <div className="row"> <div className="col-md-12"> <h2 className="question"><b>{this.props.question.question_title}</b></h2> {/* 现在直接用父组件的state,就能实时显示选中值了 */} <input type="text" className="rs" name="rs" value={this.state.active} /><br/> <ul className="answerOptions"> {rows} </ul> <hr/> </div> </div> ); } });
修改后的AnswerGrid组件
const AnswerGrid = React.createClass({ radioClick: function(e){ // 调用父组件传递的回调,把选中值传回去 this.props.onSelect(e.target.value); }, render : function(){ // 判断当前选项是否被选中,由父组件的active状态控制 const isChecked = this.props.active === this.props.answer.answer_id; return ( <li className="answerOption"> <input type="radio" onChange={this.radioClick} id={this.props.answer.answer_id} className="radioCustomButton" name={this.props.question_id} value={this.props.answer.answer_id} checked={isChecked} // 用checked属性控制选中状态 /><br/> <label className="radioCustomLabel">{this.props.answer.title}</label> </li> ); } });
关键修改点说明
- 状态提升:把原来
AnswerGrid里的active状态移到QuestionGrid,因为父组件需要使用这个值来更新自己的input。 - 回调传递:父组件定义
handleAnswerSelect方法,传递给子组件,子组件点击单选框时调用这个回调,把选中值传回父组件更新状态。 - 受控组件:
AnswerGrid的单选框变成受控组件,由父组件的active状态控制checked属性,保证选中状态和父组件数据一致。
这样修改后,QuestionGrid里的input就能实时显示当前选中的answer_id啦~
内容的提问来源于stack exchange,提问作者Jung Sun
相关产品推荐
相关产品推荐

