2016-07-18 65 views
0

我想附加一个方法来接受传入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方法应该是相当常见的,但我无法在网上找到任何东西。

谢谢!

回答

0

事实证明,这种解决方案适用:React-Native ListView renderRow issues passing props. The right way or the wrong way

如果您的高级别回调接受一个参数,你需要确保 您的匿名函数接受一个参数,以及(注:创建使用 匿名函数箭头语法自动绑定在目前情况下我们 函数的这个值)

在_renderRow功能,我需要附加参数的函数的签名(someM方法),作为道具传递下来。我这样做的只是通过箭头符号增加了一个参数:

_renderRow(rowData) { 
    return (
    <SomeComponent onPress={(args) => this.someMethod(args)} data={rowData} /> 
    ) 
} 

SomeComponentonPress,我就能够真正调用onPress方法与参数:

render() { 
    return (
    <TouchableHighlight 
    underlayColor='#EFEFEF' 
    onPress={() => this.props.onPress(this.props.data[1])}> 
     <View> 
     <Text>{this.props.data[0]}</Text> 
     </View> 
    </TouchableHighlight> 
) 
0

在渲染行中的onPress简单地做:

onPress={this.someMethod} 

这应该做的伎俩。

+0

感谢您的答复。问题是这会导致一些方法在渲染时立即被调用,这就是为什么我选择使用箭头函数:http://stackoverflow.com/questions/34226076/why-is-my-onclick-being-called- on-render-react-js或者,我试着做onPress = {_ => this.someMethod(rowData [2])},但这看起来不正确。我相信,必须有一个简单的方法来做这样的事情。 – txizzle

+0

实际上没有。只要你把它放在()上就可以了。我一直这样做,下面是一个例子,它不会立即调用它:https://rnplay.org/apps/_9C0Cw – rmevans9

+0

哦,是的,你是完全正确的 - 没有()函数不会被渲染。我的案子的问题实际上是通过了争论。如果没有onPress中的(),我无法在SomeComponent中传入数据。基本上,当我传递'onPress = {this.someMethod}'作为道具,然后在实际的SomeComponent中做'onPress = {this.props.onPress(this.props.data [1])}',React告诉我认为'this.props.data [1]'是'nil'。任何想法为什么?或者,将我的答案看作解决方案,但我很好奇为什么这种方法无效。 – txizzle

相关问题