简体   繁体   中英

Pass updated value to parent in React

Hello people at Stack Overflow!

I have two components, NewArticle and HoveringMenu .

In NewArticle I have a JSON object which looks like this:

const initialValue = Value.fromJSON({
  document: {
    nodes: [
      {
        object: 'block',
        type: 'paragraph',
        nodes: [
          {
            object: 'text',
            leaves: [
              {
                text: 'Tell your story...'
              }
            ]
          }
        ]
      }
    ]
  }
})

I have to have it in order for a package that I use to work.

In NewArticle 's state I have that initialValue as my content which I later pass down to my HoveringMenu component:

<HoveringMenu value={this.state.values.content} />

Just to clarify, content is equal to the initialValue .

And inside of the HoveringMenu component I have a bunch of functions which enables me to edit the text and change style of it etc. But when I submit the new edited text to my server it wont get updated since my submit function is in the other component, NewArticle . Which just takes the content:

content: JSON.stringify(this.state.values.content.toJSON())

from it's own state, meaning the none edited text (Tell your story...) from the initialValue variable.

So I just wonder how I can pass the new written text to the NewArticle component. Or if I should try to solve this problem some other way.

Keeping the state in NewArticle and passing the props to the HoveringMenu is a good idea but updating it in the child is not.

You should call the setState of the parent component ( NewArticle ) from the "bunch of functions" in the child component ( HoveringMenu ).

Basically, if you are having the state in the parent and passing it as a props to the child then make sure you change the state in the parent only. Otherwise, you would have to sync the state in the parent and child. (Also, you can make use of component lifecycles methods in the child component to know if the props changed or not like componentWillReceiveProps )

So, you can pass a function to the child which updates the parent state, something like this:

<HoveringMenu value={this.state.values} updateValue={this.updateValue}  />

and your updateValue function would be doing

updateValue: function(values) {
    this.setState({
        values: values
    })
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM