Passing a component in the details using the method of children

Is it possible to pass a component in the details using the children method?

I have components:

 let a = (<div>
        <button onClick={TContainer.METHOD}>TuCLIK</button>
  </div>);

 <TContainer data={ restaurantList } component={a}/>

I want to call a method in childen, but create an element in the parent. I want to transfer this component to the details.

If possible, I do not know what to write in TContainer.METHOD to call the childen method

+4
source share
1 answer

component , .
class extends React.Component, , jsx.
, , , , , :

let A = (onClick) => <div><button onClick={onClick}>TuCLIK</button></div>;
<TContainer data={ restaurantList } component={<A onClick={TContainer.METHOD} />}/>

, .

Edit
, , , .
React.

  • , this.props.children .
    - <Parant><Child/></Parent>
  • .
    - <Parent component={Child} /> <Parent component={<Child />} />
  • HOC .
    - Parent(Child)

, ( ).
, render.
:

  render() {
    return (
      <div>
        <this.props.component onClick={this.handleClick}/>
      </div>
    );
  }

, :

const Child = ({onClick}) => <div onClick={onClick}>Im a child, Click me!</div>

class Parent extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      counter: 0
    }

    this.addCount = this.addCount.bind(this);
  }

  addCount(){
    this.setState({counter: this.state.counter + 1});
  }

  render() {
    return (
      <div>
        <div>{`Count = ${this.state.counter}`}</div>
        <this.props.component onClick={this.addCount}/>
      </div>
    );
  }
}

const App = () => <Parent component={Child} />;

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Hide result
+1
source

Source: https://habr.com/ru/post/1686331/


All Articles