简体   繁体   中英

onChange event handler in ReactJS

I need to update the state based on the value of an optionally added field in react. I am unsure as how to reference the field I want to update in my existing handler, since I am using arrays for optional fields and objects for required fields. The array is called optionalfields in state, and they are rendered with the renderHelper() method.

I have tried passing in the index, but this breaks the functionality of event.

State initialization

    state = {
        fields:{
            category: "",
            type:"",
            host:"",
            context:""
        },
        optionalfields:[],
        newFieldName:""
    }

On Change Handler

handleChange = (event) => {
        const target = event.target
        if (target.name === 'newFieldName') {
            this.setState({
                newFieldName: target.value
            })
        } else if (target.name in this.state.fields) {
            this.setState(prevState => ({
                fields: {
                    ...prevState.fields,
                    [target.name]:target.value
                }
            }))
        } else {
            //Update input value
        }
    }

Render Helper method

    renderHelper() {

        return (
            this.state.optionalfields.map((field,index) => {
                return (
                    <div key={field.name}>
                        {field.name}:<input onChange={this.handleChange} type="text" name={field.name} value={this.state.optionalfields[index].value} autoComplete="off" /><button onClick={(event) => this.removeField(field.name, event)} type="button">Remove</button><br/>
                    </div>
                )
            })
        )
    }

In React using value={some_value} will make it so that you cannot type in the input field. You should use defaultValue="{some_value}"

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