React 将 Props 传递给第二级子级
2020-07-23
746
我在 React 中编码时遇到了传递 props 的问题。是的,我以前见过这个问题,但这次是第二级子组件,情况有点奇怪。我的代码(一路注释):
class EditForm extends React.Component {
handleSubmit = (event, idx) => {
event => event.preventDefault();
postData('/', {idx: idx})
.then(data => {if (data.success) {window.location = '/';}});
console.log(idx); // results printed from here
}
render() {
return (
<Form
onFinish={() => this.handleSubmit(idx)} // output 1
onFinish={() => this.handleSubmit(this.props.idx)} // output 2
>
</Form>
);
}
}
class UpdateModal extends React.Component {
render() {
return (
<Modal>
<EditForm idx={ this.props.idx } /> // value is still not undefined
</Modal>
);
}
}
输出:
// 1
useForm.js:766 ReferenceError: idx is not defined
// 2
undefined
有人能解释一下为什么我不能连续两次传递 props 吗?事实上,当它们在 UpdateModal 中时,这些值仍然有效,但之后不知何故就消失了。
提前致谢。
2个回答
您应该将事件对象传递给您的处理程序:
class EditForm extends React.Component {
handleSubmit = (event, idx) => {
event => event.preventDefault();
postData('/', {idx: idx})
.then(data => {if (data.success) {window.location = '/';}});
console.log(idx); // results printed from here
}
render() {
return (
<Form
onFinish={(event) => this.handleSubmit(event, idx)} // output 1
onFinish={(event) => this.handleSubmit(event, this.props.idx)} // output 2
>
</Form>
);
}
}
class UpdateModal extends React.Component {
render() {
return (
<Modal>
<EditForm idx={ this.props.idx } /> // value is still not undefined
</Modal>
);
}
}
Joshua
2020-07-23
class EditForm extends React.Component {
constructor(props) {
super(props);
}
// ...
}
class UpdateModal extends React.Component {
constructor(props) {
super(props);
}
// ...
}
// <EditForm idx={this.state.idx}></EditForm>
// <UpdateModal idx={this.state.idx}></UpdateModal>
山茶树和葡萄树
2020-07-23