简体   繁体   中英

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

I have a TextField and a Button (both are material-ui components) displaying on my main page. I want to be able to click the button and populate a form that includes the previous TextField and any text that had already been written in it. The code I currently have just makes a new instance of the TextField within the form, while keeping the original TextField as well. How can I bring the existing TextField over into the form without duplicating?

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

};

As you want to share data between two components you can resolve this in different ways, based in your code, a solution could be:

Your App control the data so,

in your state can add:

this.state = {
 inputData = '';
}

You need to pass an update function to your FromTextField

<FormTextField onTextUpdate={(text) => this.setState({ inputData: text })} />

Your form field must be controlled by App so you need to pass the data to be shown too:

<FormTextField data={this.state.inputData} onTextUpdate={(text) => this.setState({ inputData: text })} />

(you need to add that modification to FormTextField, they are easy)

And the last step is to do the same with Form

<Form data={this.state.inputData} onTextUpdate={(text) => this.setState({ inputData: text })} />

Inside Form you need to pass data and onTextUpdate to the FormTextField

You can refactor (text) => this.setState({ inputData: text }) to be a method in class.

EDIT

https://codesandbox.io/embed/stackoverflow-form-react-9188m you can find the implementation about I told you before.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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