首页 > 解决方案 > React Native 方法中的参数

问题描述

这是我试图理解的示例代码。

class Form extends React.Component {

  constructor (props) {
     super(props)
     this.state = {
       input: ''
     }
  }

handleChangeInput = (text) => {
    this.setState({ input: text })
  }

  render () {
    const { input } = this.state

    return (
       <View>
          <TextInput style={{height: 40, borderColor: 'gray', borderWidth: 1}}
            onChangeText={this.handleChangeInput}
            value={input}
          />
        </View>
      )
    }
 }

在这个困扰我的代码是

onChangeText={this.handleChangeInput}

在这段代码中,没有参数传递给需要文本的方法(handleChangeInput)。

有人可以在这里放灯吗。

标签: javascriptreact-native

解决方案


基本上,您传递的是对具有相同签名的函数的引用。

React 函数参考可能有助于阐明一些问题。

给定

callback = param => { /* do stuff */ };

然后

componentFn={callback};

相当于

componentFn = param => { /* do stuff */ };

componentFn={param => callback(param)}

相当于

component = param => { callback(param) } // call function that does stuff

直接引用只是删除了中间函数绑定。


推荐阅读