React brothers components by value

Brothers components by value actually indirectly through a third party to achieve the traditional values, for example, the first son of the value passed to his father, his father in this value is passed to the second son, thus achieving a brother components by value

Look at the code:

Father component code

. 1 Import from React 'REACT' ;  
 2 Import from SON1 './Son1' ;
 . 3 Import Son2 from './Son2'
 . 4  class the extends React.Component {Father
 . 5      constructor () {
 . 6          Super ();
 . 7          // give a null message 
. 8         the this .STATE = {
 . 9             message: ''
 10         }
 . 11      }
 12 is      // declare a method for receiving a value transmitted Son1 
13 is      message (MSG) {
 14       the this .setState ({
 15          message: MSG   / / put value to the message came Son1
16       })
 . 17      } 
 18 is      the render ({)
 . 19          return (
 20 is              <React.Fragment>
 21 is                      { / * Method Here we get the upper subassembly incorporated declared * / }
 22 is                  <MSG = {SON1 the this .message.bind ( the this )}> </ SON1>
 23 is                     { / * here is introduced and a second sub-assembly str declare a property value to pass over SON1 transmitted * / }
 24                  <Son2 str = { the this .state.message}> </ Son2 >
 25              </React.Fragment>
 26 is          )
 27     }
28 }
29 export default Father;

The first sub-assembly

. 1 Import from React 'REACT' ;
 2  class {SON1 the extends React.Component
 . 3      constructor () {
 . 4          Super ()
 . 5      }
 . 6      BTN (MSG) {
 . 7          // a parent component to pass this value 
. 8          the this .props.msg ( 'which is passed over Son1' )
 . 9      }
 10      the render () {
 . 11          return (
 12 is              <React.Fragment>
 13 is                  { / * write the value of a click to call the top of the button * / }
 14                  <button the onClick = { the this . btn.bind (the this )}> SON1 the button </ Button>
 15              </React.Fragment>
 16          )
 . 17      }
 18 is  }
 . 19 Export default SON1;

The second sub-assembly

. 1 Import from React 'REACT' ;
 2  class {Son2 the extends React.Component
 . 3      constructor () {
 . 4          Super ()
 . 5      }
 . 6      the render () {
 . 7          return (
 . 8              <React.Fragment>
 . 9                 { / * The second sub-assembly by props this property to pass over the parent component accepts STR * / }
 10                  <div> Son1 received value of: { the this .props.str} </ div>
 . 11              </React.Fragment>
 12 is          )
 13 is      }
 14  }
 15  
16 export default Son2;    

This enables a simple brother components by value

Guess you like

Origin www.cnblogs.com/z-j-c/p/12072278.html