假设代码(称为Answers的子组件)动态生成3个div(基于映射的数据集),每个div包含一个文本框和一个提交按钮。
如果用户在第二个文本框中键入内容并单击“提交”,如何在buttonSubmit处理程序(位于父组件中)中维护正确的绑定(从第二个文本框中获取文本)?
假设我的目标是在buttonSubmit处理程序中的警告(评论)中查看正确的文字...我该如何做到这一点?谢谢!
var Parent = React.createClass({
buttonSubmit: function(e){
e.preventDefault();
var comment = $(this).closest('.answer-container').find('.answer-textArea').val(); // get comment text
alert(comment);
},
render: function(){
return (
<div>
<Answers data={this.state.answers} onButtonSubmit={this.buttonSubmit} />
</div>
);
}
});
var Answers = React.createClass({
render: function(){
var self = this;
var answerNodes = this.props.data.map(function(answer){
return (
<div className="answer-container">
<div className="answer-comment">
<textarea className="answer-textArea" placeholder="Comment must be more than 5 words ..."></textarea>
</div>
<div className="answer-rateIt">
<input data-id={answer.AnswerID} type="number" className="rating" />
<br /><br />
<button id={answer.AnswerID} className="buttonSubmit" onClick={self.props.onButtonSubmit} >Submit</button>
</div>
</div>
);
});
return(
<div>
{answerNodes}
</div>
);
}
});
答案 0 :(得分:1)
我要做的第一件事就是将Answer标记拆分成一个单独的组件。此组件的职责是为单个答案呈现标记,并在通过提供的处理程序单击提交按钮时提供注释和评级值。评论和评级值使用refs获得。
var Answer = React.createClass({
submitHandler: function (e) {
if (this.props.hasOwnProperty('submitHandler')) {
this.props.submitHandler({
comment: this.refs.comment.getDOMNode().value,
rating: this.refs.rating..getDOMNode().value
});
}
},
render: function () {
return (
<div className="answer-container">
<div className="answer-comment">
<textarea
ref="comment"
className="answer-textArea"
placeholder="Comment must be more than 5 words ..."
></textarea>
</div>
<div className="answer-rateIt">
<input
ref="rating"
type="number"
className="rating"
/>
<br/><br/>
<button
className="buttonSubmit"
onClick={this.submitHandler}
>
Submit
</button>
</div>
</div>
);
}
});
Answsers组件将使用submitHandler呈现一组Answer组件,该commitHandler将AnswerId附加到给定的注释和评级,并通过提供的处理函数将此数据传递给父级。
var Answers = React.createClass({
render: function(){
var self = this;
var answerNodes = this.props.data.map(function(answer){
var submitHandler = function (answerData) {
if (self.props.hasOwnProperty('submitHandler')) {
self.props.submitHandler({
answerId: answer.AnswerID,
comment: answerData.comment,
rating: answerData.rating
});
}
};
return <Answer id={answer.AnswerID} submitHandler={submitHandler}/>;
});
return(
<div>
{answerNodes}
</div>
);
}
});
父母的提交处理程序然后可以通过给定对象访问数据。
var Parent = React.createClass({
buttonSubmit: function(e) {
// e.preventDefault(); Not necessary unless inside a form
var comment = e.comment;
alert(comment);
},
render: function(){
return (
<div>
<Answers data={this.state.answers} submitHandler={this.buttonSubmit} />
</div>
);
}
});