我想附加一个方法来接受传入ListView的数据。具体来说,我使用ListView React Native组件,它是_renderRow函数,它将数据源映射到不同的行。在数据源,我想在数据元素作为参数之一传递给此方法:React Native:从_renderRow中的道具传递数据源到方法
class MainComponent extends Component {
constructor(props) {
super(props)
var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = { dataSource: ds.cloneWithRows([['foo1', 'bar1'], ['foo2','bar2']])};
this._renderRow = this._renderRow.bind(this);
}
render() {
return (
<View>
<ListView
dataSource={this.state.dataSource} // [['foo1', 'bar1'], ['foo2', 'bar2']]
renderRow={this._renderRow}
/>
</View>
);
}
_renderRow(rowData) {
return (
<SomeComponent onPress={_ => this.someMethod} data={rowData} />
//Trying to call someMethod with argument 'bar1'.
//I have also tried passing in the argument here with:
// onPress={_ => this.someMethod({rowData[1]})}
)
}
someMethod(data) {
//do something with data
}
}
class SomeComponent extends Component {
render() {
return (
<TouchableHighlight
underlayColor='#EFEFEF'
onPress={this.props.onPress(this.props.data[1])}>
//Is this the correct way to pass in 'bar1' into the method?
<View>
<Text>{this.props.data[0]}</Text>
</View>
</TouchableHighlight>
)
}
}
那么,什么是做这种正确的方法是什么?我想,将数据源数据传递给onPress方法应该是相当常见的,但我无法在网上找到任何东西。
谢谢!
感谢您的答复。问题是这会导致一些方法在渲染时立即被调用,这就是为什么我选择使用箭头函数:http://stackoverflow.com/questions/34226076/why-is-my-onclick-being-called- on-render-react-js或者,我试着做onPress = {_ => this.someMethod(rowData [2])},但这看起来不正确。我相信,必须有一个简单的方法来做这样的事情。 – txizzle
实际上没有。只要你把它放在()上就可以了。我一直这样做,下面是一个例子,它不会立即调用它:https://rnplay.org/apps/_9C0Cw – rmevans9
哦,是的,你是完全正确的 - 没有()函数不会被渲染。我的案子的问题实际上是通过了争论。如果没有onPress中的(),我无法在SomeComponent中传入数据。基本上,当我传递'onPress = {this.someMethod}'作为道具,然后在实际的SomeComponent中做'onPress = {this.props.onPress(this.props.data [1])}',React告诉我认为'this.props.data [1]'是'nil'。任何想法为什么?或者,将我的答案看作解决方案,但我很好奇为什么这种方法无效。 – txizzle