Reputation:
I have a component with id
property and I would like to get the value of the id
. Here is my work.
constructor(props) {
super(props);
this.state = {
data: []
}
populate() {
for (let i = 0; i < 5; i++) {
data.push( < ChildComponent id = {
i
}
/>)
}
}
getValue() {
let tmp = data[0]
alert(tmp.id)
}
render() {
{
this.populate
}
return (
<
Button onClick = {
this.getValue
} > alert ID < /Button>
)
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
populate()
inserts five childcomponent to data.
getValue()
is where I want to alert id of the component.
undefined
is being alerted
Upvotes: 0
Views: 87
Reputation: 307
Try it like this:
constructor(props){
super(props);
}
getValue(){
alert(this.child_0.props.id)
}
render(){
return(
<>
{(new Array[5]).map((item, idx) => <ChildComponent ref={e => this['child_' + idx]} key={idx} id={idx}/>)}
<Button onClick={this.getValue}>alert ID</Button>
</>
)
}
}
Upvotes: 0
Reputation: 36564
use props.id
.Because id
is not property of component tmp
itself. Its present in props
because id
is passed as prop
here data.push(<ChildComponent id={i}/>)
getValue(){
let tmp = data[0]
alert(tmp.props.id)
}
Upvotes: 1