子组件下拉列表的React onChange事件以更新状态



在将Vanilla JS代码转换为React后,我正在尝试学习如何实现React表单。我有一个onChange,它将更新父组件的(表单(状态,如下所示。我制作了一个子组件(库(,当用户选择不同的文档时,它有自己的onChange事件,如下所示,这会影响它拥有的另一个子组件。有没有一种方法可以让我用库组件中选择的库ID更新表单状态?

class FormTemplate extends Component {
state = {
libraryId: "",
libraryName: "",
email: ""
};
handleChange = e => {
this.setState({
[e.target.name]: e.target.value
});
};
render() {
return (
<Form>
<Row>
<Col xs={6} md={6}>
<Form.Group controlId="exampleForm.ControlInput1">
<Form.Label>First Signer Email</Form.Label>
<Form.Control
type="email"
name="email"
onChange={this.handleChange}
placeholder="name@example.com"
/>
</Form.Group>
<button type="submit">POST</button>
</Col>
<Col xs={6} md={6}>
<GetLibrary/>
</Col>
</Row>
</Form>
);
}
}
export default FormTemplate;

子库模板

export class GetLibrary extends Component {
state = {
library: [],
libraryId: ""
};
componentDidMount() {
API.get("library")
.then(res => {
const library = res.data.library;
this.setState({ library });
})
.catch(err => {
console.log(err);
});
}
handleChange = e => {
console.log(e.target.value);
this.setState({
libraryId: e.target.value
});
};
render() {
const { library, libraryId } = this.state;
let document;
if (libId !== "") {
document = (
<p>
<GetDocument key={libId.toString()} libraryId={libraryId} />
</p>
);
} else {
document = <p>Choose a document</p>;
}
return (
<Fragment>
<Form.Group controlId={libraryId}>
<Form.Label>Select Library Document</Form.Label>
<Form.Control as="select" onChange={this.handleChange}>
{library.map(libdoc => (
<option key={libdoc.id.toString()} value={libdoc.id}>
{libdoc.name}
</option>
))}
</Form.Control>
{document}
</Form.Group>
</Fragment>
);
}
}
export default GetLibraryDocument;

我主要是试图从子组件获取libdoc.id和libdoc.name,以便能够将父状态更新为父窗体中的libraryId和libraryName以供提交(用于API后调用(。有没有办法实现这一点,或者我需要重组我的组件,如果有,你将如何重组/组织它们以提高效率?

提前谢谢。

您正在描述将状态从一个组件提升到另一个组件的过程;React官方文档中有一个非常全面的例子。

最新更新