你只是想在索引發生變化時傳遞索引。這允許父母更新其狀態,然後一切都更新。
將數據從dom中提取出來在其他庫中是有意義的,但React使我們很少這樣做。明智地選擇你的真理之源:-)
var C = React.createClass({
handleSelect(index){
this.props.onSelect(index);
},
render(){
var options = this.props.options
// map, but keep track of the index
.map((x, i) => [x, i])
// some filtering thing
// this also allows efficient inserts and removals by giving a good key
.filter(([x, i]) => x[0] === 'b');
return (
<div>
<input value={this.props.value} onChange={this.handleChange} />
<ul role="listbox">
{options.map(([x, i]) =>
<li key={i} onClick={e => this.handleSelect(i)}>
{this.props.renderItem(x, i)}
</li>
)}
</ul>
</div>
);
}
});
var ITEMS = ["foo", "bar", "baz", "quux", "bananas"];
var App = React.createClass({
getInitialState(){
return {selected: "baz"};
},
handleSelect(index){
// setState based on the index
// note that even though bananas is only the 3rd item rendered
// in the dom, index here will be 4 so this works
this.setState({selected: this.props.items[index]});
},
render(){
var renderItem = x => {
var cn = x === this.state.selected ? 'active' : null;
return <strong className={cn}>{x}</strong>
};
return <div>
Hello, world!
<C options={this.props.items}
renderItem={renderItem}
onSelect={this.handleSelect} value={this.state.selected} />
</div>;
}
});
jsbin
我不知道你想做什麼?有一個'componentDidMount'方法實現了DOM,你可以使用'innerText'。但是,因爲這只是創建的JSX語法,您爲什麼不直接在'render'中提取呢? – WiredPrairie 2015-03-31 11:54:31
@WiredPrairie我在問題中添加了上下文來澄清事情。 – 2015-03-31 12:24:25