【问题标题】:How to target the node instead of the node number with an onPress如何使用 onPress 定位节点而不是节点号
【发布时间】:2016-11-08 19:30:41
【问题描述】:

我有一堆用户正在被渲染到<ListView/> 中的<StatusSphere/> 组件中。

当我单击每个<StatusSpheres/> 时,我希望将它们各自的uid 打印到控制台(以便我可以进一步操作它们)。

这就是我遇到麻烦的地方;在 React 上我会使用e.target.value,甚至可以使用getAttributes。但在这里我得到的只是一个数字(例如 237 或 248.. 等),我认为它是节点号?

我发现另一个来源说你可以使用:

var ReactNativeComponentTree =require('react/lib/ReactNativeComponentTree'); ReactNativeComponentTree.getInstanceFromNode(nativeTag);

但这对我不起作用,而且看起来很奇怪。

如何轻松访问已存储在实际组件中的 uid?一定有我没遇到过的直截了当的方法。

非常感谢

export default class UserList extends Component {
  constructor() {
    super();
    this.userRef = firebase.database().ref().child('users')
    this.ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2})
    this.state = {
      users: this.ds.cloneWithRows([])
    }
  }
  componentWillMount() {
    //Checks my firebase database for the users and pushes it into the this._users array....
    this._users = []
    this.userRef.on('child_added', snap => {
      this._users.push({
        user: snap.val().username,
        isOnline: snap.val().isOnline,
        isChatter: snap.val().isChatter,
        uid: snap.val().uid
      });
      //...which then gets passed into this function...
      this.populateUsers(this._users);
    }).bind(this);
  }
  populateUsers(nodes) {
    //which then populates the state with the databases' users, which is then automatically rendered in the listview below
    this.setState({users: this.ds.cloneWithRows(nodes)});
  }
  _toChat(e) {
    console.log('************ native target *************');
    console.log(e.target);
    console.log('************ native target *************');
  }
  render() {
    return (
      <ListView
        horizontal
        enableEmptySections={true}
        dataSource={this.state.users}
        renderRow={d => <StatusSphere onPress={this._toChat}
                                      uid={d.uid}
                                      user={d.user}
                                      isOnline={d.isOnline}
                                      isChatter={d.isChatter}/>}/>
    )
  }
}

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    我不确定我是否理解你的问题,但是;

    您可以使用箭头函数调用带有额外参数的 toChat 方法。

    onPress={(e)=>{this._toChat(e,d.uid)}}
    

    【讨论】:

    • 天哪,3 小时的尝试,这就是答案.. 谢谢老兄! :)
    • 不,这是非常糟糕的记录,所以人们继续这样做并不断推荐其他人这样做。但是你永远不应该在 JSX/render 中使用 bind 或箭头函数,因为它们每次都会创建一个新函数。在此处创建一个新函数实际上会修改组件的状态,如您所知,React 组件仅重新渲染具有状态更改的组件。这是我们使用 React 的主要原因之一。这对于单个组件来说并不重要,但是当您需要生成组件数组时会很快出现问题,例如使用map 制作ListItems。
    猜你喜欢
    • 1970-01-01
    • 2017-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-18
    • 2022-09-28
    • 2022-08-16
    • 2021-06-17
    相关资源
    最近更新 更多