react中事件绑定的几种方式以及参数传递

如何进行事件绑定

第一种(绑定this)

class OcWarp extends React.Component {
            constructor(props) {
                super(props)
                this.state = { inputVal: "" }
                //为方法进行this绑定
                this.changeInput = this.changeInput.bind(this)
            }
            changeInput(e) {
                console.log(e)
                this.setState({
                    inputVal: e.target.value
                })
            }

            render() {

                return <div>
                    <input value={this.state.inputVal} onChange={this.changeInput} />
                </div>
            }

        }

方法二(将方法定义为箭头函数)

class OcWarp extends React.Component {
            constructor(props) {
                super(props)
                this.state = { inputVal: "" }
            }
            //将方法定义为箭头函数
            changeInput = (e) => {
                console.log(e)
                this.setState({
                    inputVal: e.target.value
                })
            }

            render() {
                return <div>
                    <input value={this.state.inputVal} onChange={this.changeInput} />
                </div>
            }

        }

方法三(使用箭头函数的方式调用)

 class OcWarp extends React.Component {
            constructor(props) {
                super(props)
                this.state = { inputVal: "" }
            }
            //将方法定义为箭头函数
            changeInput(e) {
                console.log(e)
                this.setState({
                    inputVal: e.target.value
                })
            }

            render() {
                return <div>
                    <input value={this.state.inputVal} onChange={()=>this.changeInput()} />
                </div>
            }

        }

如何进行参数传递

方式一(使用箭头函数并显示声明参数)

       <input value={this.state.inputVal} onChange={(e)=>this.changeInput(e,text)} />

如果采用箭头函数,想要使用e作为参数的话,必须要显示的声明,不然无法正确获取

方式二(使用bind绑定函数)

     <input value={this.state.inputVal} onChange={this.changeInput.bind(this,text)} />

如果采用bind绑定的方式,采用如上代码即可,e会作为默认参数在函数最后一个,及如上demo可以在函数定义的时候

   changeInput(text,e){
		//TODO
	}

你可能感兴趣的:(react,react.js,javascript,前端)