admin管理员组

文章数量:1392003

I'm trying to pass a button's id as an argument for a function triggered by the onPress event.

setCategory = (e) => {
    console.log(e.target.id)
}
render(){
    return(
        <Button title="News" id={15} onPress={this.setCategory}/>
    )
}

so 15 should be logged in the terminal but i'm getting undefined. This is what i would do in Reactjs but i'm new to React Native so i don't know if the syntax is wrong.

I'm trying to pass a button's id as an argument for a function triggered by the onPress event.

setCategory = (e) => {
    console.log(e.target.id)
}
render(){
    return(
        <Button title="News" id={15} onPress={this.setCategory}/>
    )
}

so 15 should be logged in the terminal but i'm getting undefined. This is what i would do in Reactjs but i'm new to React Native so i don't know if the syntax is wrong.

Share Improve this question edited Jan 11, 2019 at 5:59 Phạm Quang Mẫn asked Jan 11, 2019 at 5:54 Phạm Quang MẫnPhạm Quang Mẫn 1701 gold badge2 silver badges10 bronze badges 5
  • is this button your custom ponent. – Sarmad Shah Commented Jan 11, 2019 at 5:57
  • it's a react-native ponent – Phạm Quang Mẫn Commented Jan 11, 2019 at 5:58
  • i'm taking the id from the prop i just put the 15 in there for the sake of the demonstration – Phạm Quang Mẫn Commented Jan 11, 2019 at 6:00
  • If you show how you get the property which is put into id I can edit my answer for you. – PrimeTimeTran Commented Jan 11, 2019 at 6:06
  • so i'm actually rendering the Button in a FlatList ponent, so it should be something like this <Button title={item.name} id={item.id} onPress={this.setCategory}/> – Phạm Quang Mẫn Commented Jan 11, 2019 at 6:11
Add a ment  | 

2 Answers 2

Reset to default 3

If id es from a prop, then you can do this.

<Button title="News" id={this.props.prop_where_id_is} onPress={() => this.setCategory(this.props.prop_where_id_is)} />

Then your setCategory bees

setCategory = (e) => {
    console.log(e)
}

You can get the props with the help of 'ref'

            <Button
                id='5'
                title='sss'
                ref={ref => this.button = ref}
                onPress={() => console.log(this.button.props.id)}
            />

in your case

             onPress = (id) => {
               console.log(id);
              }
                ...
                 <Button
                    id='5'
                    title='sss'
                    ref={ref => this.button = ref}
                    onPress={() => 
                      this.onPress(this.button.props.id)
                    }
                    />

本文标签: javascriptHow to pass Button39s id in onPressReact NativeStack Overflow