繁体   English   中英

单击按钮后如何将带有输入数据的TextField传递到表单?

[英]How to pass TextField with entered data into form after clicking a button?

我的主页上显示了一个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}

        );
    }
};

Form.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>
    );
}

};

当您要在两个组件之间共享数据时,可以根据您的代码以不同的方式解决此问题,解决方案可以是:

您的App控制数据,

在您的状态下可以添加:

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内部,您需要将dataonTextUpdate传递给FormTextField

您可以将(text) => this.setState({ inputData: text })重构为类中的方法。

编辑

https://codesandbox.io/embed/stackoverflow-form-react-9188m您可以找到我之前告诉您的实现。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM