Undefined不是this.state中的对象 - ReactNative

时间:2017-03-27 06:56:01

标签: javascript android react-native

我是ReactNative的新用户,我在undefined is not a object中收到错误this.state.rows我试图在用户点击{{}时动态添加View {1}}。我尝试使用 this而不是使用Button我使用了getInitialState,但我继续说错误。这是我的代码

constructor(props)

感谢您的帮助!

3 个答案:

答案 0 :(得分:17)

您需要将this绑定到函数addRow,如下所示:

<TouchableHighlight onPress={ this.addRow.bind(this) } >
  <Text>Add</Text>
</TouchableHighlight>

或创建一个匿名函数来自动绑定它:

<TouchableHighlight onPress={ () => this.addRow() } >
  <Text>Add</Text>
</TouchableHighlight>

有关说明,请参阅this

答案 1 :(得分:1)

你也可以这样做。

export default class CustomCard extends React.Component{
    constructor(props) {
        super(props);

        // This binding is necessary to make `this` work in the callback
        this.functionName= this.handleUpvote.bind(this);
    }
}

要调用该函数,您可以这样调用它。

<TouchableHighlight onPress={this.functionName} >
  <Text>Add</Text>
</TouchableHighlight>

答案 2 :(得分:1)

<TouchableHighlight onPress={ this.addRow.bind(this) } >
  <Text>some text</Text>
</TouchableHighlight>