我的主页上显示了一个 TextField 和一个 Button (都是 Material-ui 组件)。我希望能够单击该按钮并填充一个表单,其中包含先前的 TextField 以及已写入其中的任何文本。我当前的代码只是在表单中创建了 TextField 的新实例,同时也保留了原始的 TextField。如何将现有的 TextField 引入表单而不进行复制?
FormTextField.js
const FormTextField = props => {
return (
<TextField
fullWidth={true}
multiline={true}
rows="10"
variant="outlined"
>
{props.data}
</TextField>
)
}
export default class FormTextField extends Component {
render() {
data={this.props.data} />
return (
{FormTextField}
);
}
};
表单.js
const Form= () => {
return (
<FormLabel">Input Text...</FormLabel>
<FormTextField />
);}
export default Form;
App.js
const AddButton= (props) => {
return (
<Button variant="contained" onClick={props.onClick}>
New Interaction
</Button>
)
}
export default class App extends Component {
constructor(props) {
super(props);
this.state = {show: false};
}
showForm = () => {
this.setState({
show: true,
});
}
render() {
return(
<Fragment>
<Header />
<FormTextField />
<AddButton onClick={this.showInteractionForm} />{this.state.show ?
<Form /> : null}
</Fragment>
);
}
};
最佳答案
当您想要在两个组件之间共享数据时,您可以根据代码以不同的方式解决此问题,解决方案可能是:
您的应用
控制数据,
在您所在的州可以添加:
this.state = {
inputData = '';
}
您需要将更新函数传递给您的FromTextField
<FormTextField onTextUpdate={(text) => this.setState({ inputData: text })} />
您的表单字段必须由App
控制,因此您也需要传递要显示的数据:
<FormTextField data={this.state.inputData} onTextUpdate={(text) => this.setState({ inputData: text })} />
(您需要将该修改添加到 FormTextField,它们很简单)
最后一步是对 Form
执行相同的操作
<Form data={this.state.inputData} onTextUpdate={(text) => this.setState({ inputData: text })} />
在Form
内部,您需要将data
和onTextUpdate
传递给FormTextField
您可以将 (text) => this.setState({ inputData: text })
重构为类中的方法。
编辑
https://codesandbox.io/embed/stackoverflow-form-react-9188m你可以找到我之前告诉过你的实现。
关于javascript - 单击按钮后如何将包含输入数据的 TextField 传递到表单中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57012831/