React (10) React Form Element Application Method

16, form

Write a summary before

  1. Value changes are triggered by onChange events (including text entry boxes, radio, checkbox);
  2. Checked or not is achieved by setting checked HTML elements equal to a required state value (so the expression results in true, so checked='true'is selected).

[form] Label:

If you use the form tag, it will automatically trigger the page jump when submitting through the submit button, but this is usually not needed;

The solution is to add an onSubmit event, such as <form onSubmit={this.submit}>, in which the default submission behavior is prevented by e.preventDefault().

Sample code:

class HelloWord extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            name: ''
        }
        this.submit = this.submit.bind(this)
    }

    render() {
        return <form onSubmit={this.submit}>
            <label>
                male
                <input type="radio" name='gender' value='male'/>
            </label>
            <label>
                female
                <input type="radio" name='gender' value='female'/>
            </label>
            <input type="submit"/>
        </form>
    }

    submit(e) {
        console.log(arguments)
        e.preventDefault();
    }
}

[input[type=text]] tag:

By default, through value=this.state.xxx binding, is a one-way binding. That is to say, changing the value stored in state can automatically modify the value of input, but the user can not modify the value of input successfully.

Users who want to enter values must set onChange events in order to achieve bidirectional binding.

Sample code:

class HelloWord extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            value: ''
        }
        this.valueChange = this.valueChange.bind(this)
    }

    render() {
        return <form onSubmit={this.submit}>
            <input type="text" value={this.state.value} onChange={this.valueChange}/>
            <br/>
            //The value of the input box:{this.state.value}
        </form>
    }

    valueChange(e) {
        this.setState({
            value: e.target.value
        })
    }
}

[textarea] label:

Use the same method as input[type=text], slightly.

[input[type=radio]] label:

Note that the value settings for radio s and checkbox es are generally different.

The reason is that the value attribute of radio indicates that when you select the radio box, the value of the radio box, and when you need to indicate that I selected the radio box, should be checked by checked = true|'check'.

Sample code:

class HelloWord extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            gender: 'male'
        }
        this.select = this.select.bind(this)
    }

    render() {
        return <form>
            <label>
                male
                {/* You can return true to indicate selection */}
                <input type="radio" name='gender' value='male'
                       checked={this.state.gender === 'male'}
                       onChange={this.select}/>
            </label>
            <label>
                female
                {/* You can also return checked to indicate selection */}
                <input type="radio" name='gender' value='female'
                       checked={this.state.gender === 'female' ? 'checked' : ''}
                       onChange={this.select}/>
            </label>
            <br/>
            //The gender you are currently choosing is:{this.state.gender}
        </form>
    }

    select(e) {
        this.setState({
            gender: e.target.value
        })
    }
}

[input[type=checkbox]] tag:

This is obviously even more troublesome. He behaves in the checked/unchecked state, which is the same as radio s.

The problem is that checkbox may have multiple variables under a name attribute.

So you need an array to store who is currently checkbox selected.

For example: gender: ['male','female'],

Then we can judge the existence and nonexistence by indexOf (xx) > - 1 (- 1 means nonexistence).

Sample code:

class HelloWord extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            gender: ['male', 'female']
        }
        this.select = this.select.bind(this)
    }

    render() {
        return <form>
            <label>
                male
                {/* You can return true to indicate selection */}
                <input type="checkbox" name='gender' value='male'
                       checked={this.state.gender.indexOf('male') > -1}
                       onChange={this.select}/>
            </label>
            <label>
                female
                {/* You can also return checked to indicate selection */}
                <input type="checkbox" name='gender' value='female'
                       checked={this.state.gender.indexOf('female') > -1}
                       onChange={this.select}/>
            </label>
            <br/>
            //The gender you are currently choosing is:{this.state.gender.join(',')}
        </form>
    }

    select(e) {
        // Get the value and index first
        let v = e.target.value
        let i = this.state.gender.indexOf(v)
        // Remove or add
        if (i === -1) {
            this.state.gender.push(v)
        } else {
            this.state.gender.splice(i, 1)
        }
        // Finally, you have to set State to trigger render.
        this.setState({
            gender: this.state.gender
        })
    }
}

Of course, it can also be stored in the way of objects. It is simpler to write words, but it may be more troublesome to fetch data, such as examples:

class HelloWord extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            gender: {
                male: false,
                female: false
            }
        }
        this.select = this.select.bind(this)
    }

    render() {
        return <form>
            <label>
                male
                <input type="checkbox" name='gender' value='male'
                       checked={this.state.gender.male}
                       onChange={this.select}/>
            </label>
            <label>
                female
                <input type="checkbox" name='gender' value='female'
                       checked={this.state.gender.female}
                       onChange={this.select}/>
            </label>
            <br/>
            //The gender you currently choose is: {JSON. stringify(this.state.gender)}
        </form>
    }

    // The following are reusable writings (that is, multiple different checkbox es can reuse this function)
    select(e) {
        let v = e.target.value
        let name = e.target.name
        this.state[name][v] = !this.state[name][v]
        this.setState({
            [name]: this.state[name]
        })
    }
}

[select] label:

The biggest difference between select tags and Vue tags is that:

  1. When the value of the select tag in Vue is set to an empty string, the select tag will not select any option.
  2. When the value of select tag is set to empty string 3 in React, the first option tag is selected by default.
  3. Whether the value of the value bound by the select tag is set to an empty string, or to a null, or to a value that does not exist in the option tag, React sets the value bound by the select tag to an empty string.
  4. Then because when the value of the select tag binding is an empty string, the first option tag is selected by default on the page vision.
  5. If you take the value of select at this point, you get an empty string; but if you take the value through the select tag, you get the value of the first option.

That is to say, when the value is an empty string, the effect displayed on the page is different from the actual value!

So you need to manually set the value of the DOM tag to an empty string through js.

Specific solutions are as follows (including the use of select tags):

class HelloWord extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            gender: ''
        }
        this.select = this.select.bind(this)
    }

    render() {
        return <div>
            <select value={this.state.gender} ref={input => {
                this.DOM = input
            }} onChange={this.select} id='abc'>
                <option value="male">male</option>
                <option value="female">female</option>
            </select>
            <br/>
            //The gender you are currently choosing is:{this.state.gender}
            <button onClick={this.setGender.bind(this)}>Click No Settings gender</button>
        </div>
    }

    // The following is a general way of writing
    select(e) {
        let v = e.target.value
        this.setState({
            gender: v
        })
    }

    setGender() {
        this.setState({
            gender: ''
        })
    }

    // If the select is empty, you need to get the element manually through ref, and then set the value to be empty, so that the default value is not selected.
    componentDidUpdate(preProps, preState) {
        console.log('componentDidUpdate', arguments)
        if (this.state.gender === '') {
            this.DOM.value = ''
        }
    }

    // If it's initially empty, you also need to configure a wave manually here, which is a function that executes at the end of the component's lifecycle when it's created.
    componentDidMount() {
        console.log('componentDidMount')
        if (this.state.gender === '') {
            this.DOM.value = ''
        }
    }
}

Keywords: React Attribute Vue JSON

Added by method_man on Thu, 16 May 2019 01:15:38 +0300