What's the right way to pass form element state to sibling/parent elements?

后端 未结 10 777
情话喂你
情话喂你 2020-11-29 15:04
  • Suppose I have a React class P, which renders two child classes, C1 and C2.
  • C1 contains an input field. I\'ll refer to this input field as Foo.
  • M
10条回答
  •  广开言路
    2020-11-29 15:34

    1. The right thing to do is to have the state in the parent component, to avoid ref and what not
    2. An issue is to avoid constantly updating all children when typing into a field
    3. Therefore, each child should be a Component (as in not a PureComponent) and implement shouldComponentUpdate(nextProps, nextState)
    4. This way, when typing into a form field, only that field updates

    The code below uses @bound annotations from ES.Next babel-plugin-transform-decorators-legacy of BabelJS 6 and class-properties (the annotation sets this value on member functions similar to bind):

    /*
    © 2017-present Harald Rudell  (http://www.haraldrudell.com)
    All rights reserved.
    */
    import React, {Component} from 'react'
    import {bound} from 'class-bind'
    
    const m = 'Form'
    
    export default class Parent extends Component {
      state = {one: 'One', two: 'Two'}
    
      @bound submit(e) {
        e.preventDefault()
        const values = {...this.state}
        console.log(`${m}.submit:`, values)
      }
    
      @bound fieldUpdate({name, value}) {
        this.setState({[name]: value})
      }
    
      render() {
        console.log(`${m}.render`)
        const {state, fieldUpdate, submit} = this
        const p = {fieldUpdate}
        return (
          
    {/* loop removed for clarity */} ) } } class Child extends Component { value = this.props.value @bound update(e) { const {value} = e.target const {name, fieldUpdate} = this.props fieldUpdate({name, value}) } shouldComponentUpdate(nextProps) { const {value} = nextProps const doRender = value !== this.value if (doRender) this.value = value return doRender } render() { console.log(`Child${this.props.name}.render`) const {value} = this.props const p = {value} return } }

提交回复
热议问题