我有一个关于 props 和函数组件的看似微不足道的问题。基本上,我有一个容器组件,它在用户单击按钮触发的状态更改时呈现模态组件。模态是一个无状态函数组件,其中包含一些需要连接到容器组件中的函数的输入字段。
我的问题:当用户与无状态 Modal 组件内的表单字段交互时,如何使用父组件内的函数来更改状态?我是否错误地传递了 Prop ?
容器
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>
);
};
示例:假设我想从 Modal 组件中调用 this.firstNameChange
。我想将 props 传递给函数组件的“解构”语法让我有点困惑。即:
const SomeComponent = ({ someProps }) => {//... };
最佳答案
您需要为每个需要调用的函数分别传递每个 prop
<CreateProfile
onFirstNameChange={this.firstNameChange}
onHide={close}
show={this.state.showModal}
/>
然后在 CreateProfile 组件中,您可以执行以下操作
const CreateProfile = ({onFirstNameChange, onHide, show }) => {...}
通过解构,它将匹配的属性名称/值分配给传入的变量。名称只需要与属性匹配
或者只是做
const CreateProfile = (props) => {...}
并在每个地方调用 props.onHide
或您尝试访问的任何 prop。
关于javascript - react : Passing props to function components,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39963565/