Home>

From parent component&Parent>to child components<ChildeOne>and&Child;Two>
Rendering.
I want to pass<ChildeOne>data to<ChildeTwo> ;.

<Parent>⇒<ChildeOne>
Is passing characters and functions

//&lt;Parent&gt;
  return (
      &lt;ChileOne value = {i}
                onClick = {() =&gt;this.handleClick (i)}
      /&gt;);
//&lt;ChildeOne&gt;
export default function ChileOne (props) {
  return (
    &lt;button onClick = {props.onClick}&gt;
      {props.value}
    &lt;/button&gt;
  );
}

<Parent>⇒<ChileTwo>
I want to display ChildeOne's data, but it doesn't work

//&lt;Parent&gt;
  handleClick (i) {
    console.log (i)
    return&lt;ChildeTwo value = {i} /&gt ;;
  }
//&lt;ChildeTwo&gt;
export default class ChildeTwo extends React.Component {
  constructor (props) {
    super (props);
    this.state = {
      output: "",
    };
  }
  render () {
    return (
      &lt;div&gt;
       &lt;div&gt;{this.state.output}&lt;/div&gt;
      &lt;/div&gt;
    );
  }
}


Since you can get the expected value in handleClick ()
I don't think I can receive it at ChildeTwo, but I'm not sure.

  • Answer # 1

    ChildeTwo must be defined in render (), not in handleClicke (i) of Parent.

    If you are trying to display in ChildeTwo which ChileOne was clicked,
    I think that it will be displayed by adding State like clickedNumber to Parent and setState with handleClick (i).

    //<Parent>
      constructor (props) {
        super (props);
        this.state = {
          clickedNumber: 0,
        };
      }
      handleClick (i) {
        console.log (i)
        this.setState ({clickedNumber: i});
      }
      return (
          <ChileOne value = {i}
                    onClick = {() =>this.handleClick (i)}
          />
          <ChildeTwo value = {this.state.clickedNumber} />
      );
    //<ChildeTwo>
    export default class ChildeTwo extends React.Component {
      constructor (props) {
        super (props);
        this.state = {
          output: "",
        };
      }
      render () {
        return (
          <div>
           <div>{this.state.output}</div>
           <div>{this.props.value}</div>// Display the value set in Parent
          </div>
        );
      }
    }