我有一个关于道具和功能组件的看似微不足道的问题。基本上,我有一个容器组件,它在用户单击按钮触发的状态更改时呈现模态组件。模态是一个无状态函数组件,其中包含一些需要连接到容器组件内部函数的输入字段。
我的问题:当用户与无状态模态组件内的表单字段交互时,如何使用父组件内的函数来更改状态?我是否错误地传递了道具?
容器
export default class LookupForm extends Component {
constructor(props) {
super(props);
this.state = {
showModal: false
};
}
render() {
let close = () => this.setState({ showModal: false });
return (
... // other JSX syntax
<CreateProfile fields={this.props} show={this.state.showModal} onHide={close} />
);
}
firstNameChange(e) {
Actions.firstNameChange(e.target.value);
}
};
功能(模态)组件
const CreateProfile = ({ fields }) => {
console.log(fields);
return (
... // other JSX syntax
<Modal.Body>
<Panel>
<div className="entry-form">
<FormGroup>
<ControlLabel>First Name</ControlLabel>
<FormControl type="text"
onChange={fields.firstNameChange} placeholder="Jane"
/>
</FormGroup>
);
};
示例:说我想打电话this.firstNameChange
来自模态组件内。我想将 props 传递给函数组件的“解构”语法让我有点困惑。 IE:
const SomeComponent = ({ someProps }) = > { // ... };
您需要为需要调用的每个函数单独传递每个道具
<CreateProfile
onFirstNameChange={this.firstNameChange}
onHide={close}
show={this.state.showModal}
/>
然后在 CreateProfile 组件中您可以执行以下操作
const CreateProfile = ({onFirstNameChange, onHide, show }) => {...}
通过解构,它会将匹配的属性名称/值分配给传入的变量。名称只需与属性匹配
或者只是做
const CreateProfile = (props) => {...}
并在每个地方打电话props.onHide
或您尝试访问的任何道具。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)