我正在使用一组字符串类别来创建输入复选框。选中输入框会告诉我您要包含该类别,取消选中一个输入框会告诉我您不想包含该类别。
问题是,我不知道被点击的对象的引用是什么。我怎么弄清楚参考?
我想将这个ref传递给我的父类,以便它可以在我的类别数组中找到'ref'的索引,并将其拼接出来。结果是我的filteredCategories数组将删除该项目,如果它不是
则添加它var HeaderCategories = React.createClass({
handleChange:function(e){
// I know what was clicked through e.target
// but I'd like to know the ref of what was clicked
// so that I can do somthing like the below:
this.props.filterTable(this.refs[e.target.ref])
},
render: function(){
var categories = this.props.allCategories.map(function(category){
return (
<label key={category}>{category}
<input type="checkbox" ref={category} onChange={this.handleChange}/>
</label>
)}.bind(this))
return (
<div className="categories __header" >{categories}</div>
);
}});
var Table = React.createClass({
allCategories: ["apples","oranges","bananas"]
componentDidMount:function(){
this.setState({filteredCategories:this.allCategories})
},
getInitialState:function(){
return {filteredCategories:this.allCategories}
},
filterTable:function(category){
// If I have the ref then I can use a splice and remove it from my filtered Categories
//this is pseudo code, havent checked if it works
var index = filteredCategories.indexOf(category)
var filteredCategories.splice(index,filteredCategories.length)
this.setState(filteredCategories:filteredCategories)
},
render:function(){
return <Header filterTable={this.filterTable} allCategories={this.allCategories}>
}
})
答案 0 :(得分:2)
从onClick回调的事件参数中获取对组件的引用没有好办法。你最好的选择是将类别索引或名称称为回调,就像这样(在这个例子中,我只传回索引)
handleChange:function(e, categoryIndex){
// `categoryIndex` was curried in the click handler
// of each checkbox in the render function below so
// the filterTable callback should accept the index.
this.props.filterTable(categoryIndex);
},
render: function(){
var categories = this.props.allCategories.map(function(category, index){
return (
<label key={category}>{category}
<input type="checkbox" ref={category} onChange={this.handleChange.bind(this, index)}/>
</label>
)}, this); // map's second param is thisArg
return (
<div className="categories __header" >{categories}</div>
);