Reputation: 1636
I've imported a custom component
into my screen
and rendered it in the render()
function. Then, created a ref
to that custom component. Now, the render()
function simply looks like this.
render() {
return (
<View>
<MyComponent ref={component => this.myComponent1 = component} />
<MyComponent ref={component => this.myComponent2 = component} />
<MyComponent ref={component => this.myComponent3 = component} />
</View>
)
}
Then, In the same screen
file, I've created another function to access the state of my custom component. I wrote it like this.
myFunction = (ref) => {
ref.setState({ myState: myValue })
}
Then, I want to call that function for those separate components separately like this. (In the screen
file)
this.myFunction(this.myComponent1)
this.myFunction(this.myComponent2)
this.myFunction(this.myComponent3)
But, it does not work. It gives me the following error.
null is not an object (evaluating 'ref.setState')
Actually what I need this myFunction
to do is,
this.myComponent1.setState({ myState: myValue })
this.myComponent2.setState({ myState: myValue })
this.myComponent3.setState({ myState: myValue })
The state myState
is in the component
while I want to access it through the myFunction()
in my screen
file.
Can you please help me to solve this problem?
Upvotes: 0
Views: 1375
Reputation: 466
Inside your component, in the componentDidMount function please add
componentDidMount() {
this.props.refs(this)
}
setState(key, value){
this.setState({[key]:value})
}
and please change the ref param to refs
<MyComponent refs={component => this.myComponent1 = component} />
myFunction = (ref) => {
ref.setState('myState', 'myValue')
}
Upvotes: 0
Reputation: 6879
This is not good practice to setState of child component from parent component. I am assuming you want to set some value to your child component's state by trying this approach.
You can keep these values in your local state and pass it to props and your child component will re-render / get updated value there.
class Component {
constructor() {
this.state = {
myValues: {
component1: "abc",
component2: "xyz",
component3: "123",
}
}
}
myFunction(componentName, newValue) {
this.setState({
myValues: {
...this.state.myValues,
[componentName]: newValue
}
})
}
render() {
return (
<View>
<MyComponent value={this.state.myValues.component1} />
<MyComponent value={this.state.myValues.component2} />
<MyComponent value={this.state.myValues.component3} />
</View>
)
}
};
Upvotes: 1
Reputation:
First make sur that MyComponent is a component and not a stateless Component, then, to change states, try this :
myFunction = (ref) => {
ref.current.setState({ myState: myValue }
}
and of course , for it to work, your component need to be already mounts, If you try for example to call this in the constructor, it will not work
Upvotes: 0