如何解决传递道具-未定义-REACT
我不确定该怎么做。本质上,我只是希望传递当前状态作为将其传递到组件树的一种道具。
父级是一个类组件,这是我开始向下传递数据的地方:
状态和设置状态有效。当我在提交表单后控制台日志时,它显示了正确的数据,但是子级似乎无法访问它。
父组件中的状态:
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
name: "",email: "",info: ""
}
}
};
}
<form>
<input
type="text"
name="name"
required=""
value={this.state.name.value}
onChange={this.changeHandler}
/>
<label>name</label>
</input>
changeHandler = event => {
const name = event.target.name;
const value = event.target.value;
this.setState({
...this.state.[name]: {
...this.state[name],value
});
作为回报
<ExampleComponent2 //An imported component that needs to access the props defined in here
name={this.state.name}
email={this.state.email}
info={this.state.info}
/>
然后在ExampleComponent2 console.log(props.name)中返回未定义。
我还希望将道具传递到ExampleComponent2内部的另一个组件
<Child
name={props.name}
email={props.email}
idinfo{props.info}
/>
但是当我尝试在所有子组件中控制台记录道具时,它会返回未定义的状态。
解决方法
- 如果使用功能组件,则必须将props定义为功能组件的参数
示例:
const Component = (props) => {
return <ExampleComponent
name={props.name}
email={props.email}
idinfo{props.info}
/>
}
- 如果您使用的是类组件,则必须是this.props。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。