0

I have read this answer, but I want to change the structur of code a little bit,

actually I want to set parent state from child component but i don't want to add any function in parent component

actually the expected result looks like :

class Parent extends React.Component {
  constructor(props) {
    super(props)
    this.state={modalVisible:false}
  }

  render() {
    return (
      <Child modalVisible={this.state.modalVisible} />
      <Button onClick={()=>this.setState({modalVisible:true})/>
    )
  }
}

class Child extends React.Component {

  handler(e) {
    //handle parent moadlVisible state to false again
  }

  render() {
    return
      <Modal
        modalVisible = {this.props.modalVisible}>
        <Button title="Close Modal" onPress={()=>this.handler(e)}/>
      </Modal>
  }
}

so I want to make it easy to call the child component without add some function in parent to handle the child component itself, even for closing the modal of child component

Is there a way to achieve what I want?

flix
  • 1,688
  • 3
  • 34
  • 64

1 Answers1

0

If you don't want any connection between the 2 components at all, then you may have to use a global state store, such as redux.

Docs can be found here:

https://redux.js.org/introduction

Redux creates a global state instead of local state between all of the components. It does require a little configuration but once you have it fully integrated, you can handle your scenario. Also as your components grow, it'll be easier to keep track of state.

Why can't I just use events?

Quote in a question here..

react.js custom events for communicating with parent nodes

The React way would be to pass callbacks down to children explicitly via props — . There's no support for custom events w/ bubbling in React.

The reactive programming abstraction is orthogonal:

Programming interactive systems by means of the observer pattern is hard and error-prone yet is still the implementation standard in many production environments. We present an approach to gradually deprecate observers in favor of reactive programming abstractions. Several library layers help programmers to smoothly migrate existing code from callbacks to a more declarative programming model.

A horrid way to do it in my eyes would possibly be to use Async Storage

to store the key value, but I'm not going to suggest that.

JRK
  • 3,686
  • 1
  • 13
  • 19
  • I've read about redux, but it's mean my component only can be used for redux project right? actually i want to create a `custom alert` component using `modal`, – flix Sep 20 '18 at 08:58
  • I'm not fully understanding your meaning of redux project? Redux creates a global store. You can connect your components to the global store, or/and you can use local state as well – JRK Sep 20 '18 at 09:03