【发布时间】:2020-06-23 17:11:06
【问题描述】:
我有一个父组件,它保存状态,维护输入框中输入的内容。但是,我无法在输入框中输入任何内容。输入框位于我的子组件中,输入框的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;
【问题讨论】:
-
请将子组件中的 onChange={props.handleChange} 改为 onChange={(e) => { props.handleChange(e) } }
-
在父组件中改变你的handleChange函数并将this.setState({ value: e.target.value })改为this.setState({ value: e })
标签: javascript reactjs input