我有来自输入的<form>
值的子组件。需要在父组件中传递和呈现。具有onSubmit
方法,该方法适用于子级,但似乎不适用于父级组件。
怎么了?
我正在尝试在<input>
(父级)中渲染<h1>
(子级)的值。
Child.js
state = {
title : ''
}
onSubmit = (e) => {
e.preventDefault();
this.props.textChange(this.state.title);
this.setState({ title: '' });
};
onChange = (e) => this.setState({ title: e.target.value });
render() {
return (
<div>
<form
onSubmit={this.props.onSubmit}>
<input
type="text"
name="title"
placeholder="your tex here..."
value={this.state.title}
onChange={this.onChange}
/>
<input
type="submit"
value ="Submit"
/>
</form>
</div>
)
}
}
export default Text
Parent.js
class App extends Component {
state = {
colors: [],
text: 'title'
};
textChange = (title) => {
console.log(title);
this.setState({ text: title });
}
return (
<div className="App">
<h1 className="title">{this.state.text}</h1>
<Text textChange={this.textChange}/>
</div>
答案 0 :(得分:3)
props用于访问父方法/值
将{this.props.onSubmit}
更改为{this.onSubmit}
,因为onSubmit是孩子的方法
答案 1 :(得分:1)
从props
中删除onSubmit={this.props.onSubmit}
。道具用于从父级访问数据。在这种情况下,onSubmit
函数位于Child.js
文件而非Parent.js
文件的本地。
state = {
title: ''
}
onSubmit = (e) => {
e.preventDefault();
this.props.textChange(this.state.title);
this.setState({
title: ''
});
};
onChange = (e) => this.setState({
title: e.target.value
});
render() {
return ( <
div >
<
form onSubmit = {
this.onSubmit // REMOVED .props
} >
<
input type = "text"
name = "title"
placeholder = "your tex here..."
value = {
this.state.title
}
onChange = {
this.onChange
}
/>
<
input type = "submit"
value = "Submit" /
>
<
/form> < /
div >
)
}
}
export default Text
答案 2 :(得分:1)
您正在尝试从道具中调用onSubmit
方法,并将此方法放在子组件中。相反,您应该直接在this
对象上调用它。像这样:
<form
onSubmit={this.onSubmit}>
答案 3 :(得分:0)
您正在访问未传递给子组件的道具,则应将this.props.onSubmit更改为this.onSubmit。
state = {
title : ''
}
onSubmit = (e) => {
e.preventDefault();
this.props.textChange(this.state.title);
this.setState({ title: '' });
};
onChange = (e) => this.setState({ title: e.target.value });
render() {
return (
<div>
<form
onSubmit={this.onSubmit}>
<input
type="text"
name="title"
placeholder="your tex here..."
value={this.state.title}
onChange={this.onChange}
/>
<input
type="submit"
value ="Submit"
/>
</form>
</div>
)
}
}
export default Text