[英]Unable to type in text box when passing onChange prop from parent to child in React
我有一个包含 state 的父组件,它维护输入框中输入的内容。 但是,我无法在输入框中输入任何内容。 输入框位于我的子组件中,输入框的onChange和value存放在我的父组件中。
有什么方法可以将所有表单逻辑/输入数据存储在我的父组件上,并通过我的子组件访问它?
这是我的父组件代码的一部分:
export class Search extends React.Component {
constructor(props) {
super(props);
this.state = {
value: '',
screenType: 'init',
series: [],
isLoading: true,
title: '',
};
this.handleChange = this.handleChange.bind(this);
this.searchAPI = this.searchAPI.bind(this);
this.clickSeries = this.clickSeries.bind(this);
}
handleChange(e) {
this.setState({
value: e.target.value,
});
}
onKeyPress = (e) => {
if (e.which === 13) {
this.searchAPI();
}
};
async searchAPI() {
...some search function
}
render() {
return (
<Init onKeyPress={this.onKeyPress} value={this.state.value} onChange={this.handleChange} search={this.searchAPI} />
);
}
这是我的子组件的一部分:
function Init(props) {
return (
<div className="container">
<div className="search-container-init">
<input
onKeyPress={props.onKeyPress}
className="searchbar-init"
type="text"
value={props.value}
onChange={props.handleChange}
placeholder="search for a TV series"></input>
<button className="btn-init" onClick={props.search}>
search
</button>
</div>
</div>
);
}
export default Init;
在您的子组件中,您使用的是 props.handleChange,但在您的父组件中。 您将其作为 onChange 传递。 使用与传递值/函数相同的名称。 它应该像 props.onChange! 一个需要注意的愚蠢错误
子项中使用的 function 名称不正确。 onChange
道具传递给父级中的子级,并在子级中使用它作为handleChange
。
此外,如果使用 ES6 function 定义,则不需要显式绑定。
这是更新的代码:
搜索.js
export class Search extends React.Component {
constructor(props) {
super(props);
this.state = {
value: '',
screenType: 'init',
series: [],
isLoading: true,
title: '',
};
}
const handleChange = (e) => {
this.setState({
value: e.target.value,
});
}
const onKeyPress = (e) => {
if (e.which === 13) {
this.searchAPI();
}
};
const async searchAPI = () => {
...some search function
}
render() {
return (
<Init onKeyPress={this.onKeyPress} value={this.state.value} handleChange={this.handleChange} search={this.searchAPI} />
);
}
子组件:
function Init(props) {
return (
<div className="container">
<div className="search-container-init">
<input
onKeyPress={props.onKeyPress}
className="searchbar-init"
type="text"
value={props.value}
onChange={(e) => props.handleChange(e)}
placeholder="search for a TV series"></input>
<button className="btn-init" onClick={props.search}>
search
</button>
</div>
</div>
);
}
export default Init;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.