我試圖通過實現Thinking in React來試驗reactjs多個字段組件,但無法找出爲什麼在這裏調用多次的子方法。防止在React JS中多次調用方法
var i = 0;
class SearchBar extends Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange(key) {
//this method is called multiple times during Render()
console.log(i++);
return function(e) {
var value = key !== 'inStockOnly' ? e.target.value : e.target.checked;
this.props.onUserInput(
key,
value
);
}.bind(this);
}
render() {
return (
<form>
<input type="search" value={this.props.filterText} placeholder="Search ..." ref={(input) => {input.focus();}} onChange={this.handleChange('filterText')} />
<p>
<input type="checkbox" checked={this.props.inStockOnly} onChange={this.handleChange('inStockOnly')} />
{' '}
Only show products in stock
</p>
</form>
);
}
}
class FilterableProducts extends Component {
constructor(props) {
super(props);
this.state = {
filterText: '',
inStockOnly: false
};
this.handleInput = this.handleInput.bind(this);
}
handleInput(key, value) {
/*var state = {};
state[key] = value;
console.log(state);
this.setState(state);*/
//above is what I am trying to do later on but still stuck on why setState does not work
//test
this.setState({
filterText: 'foo',
inStockOnly: true
});
}
render() {
return (
<SearchBar filterText={this.state.filterText} inStockOnly={this.state.inStockOnly} onUserInput={this.handleInput} />
);
}
}
//updated handleChanged
handleChange(key, e) {
var value = key !== 'inStockOnly' ? e.target.value : e.target.checked;
this.props.onUserInput(
key,
value
);
}
//updated handleInput
handleInput(key, value) {
//var state = {};
//state[key] = value;
//this.setState(state);
//console.log(state);
//above is what I am trying to do
//test
this.setState({
filterText: 'g',
inStockOnly: true
});
}
<!--i changed the event listener to this
now its not called directly
-->
<input type="search" value={this.props.filterText} placeholder="Search ..." ref={(input) => {input.focus();}} onChange={(e)=>this.handleChange('filterText', e)} />
任何意見讚賞的
請參閱我的編輯。你的功能也應該被調用。它只會在輸入變爲現在而不是渲染時調用。 –