Suppose there is a parent block

class Parent extends React.Component { render() { retrun ( <div> <Child /> <Logs /> </div> ) } } //Покупка чего-либо class Child extends React.Component { state = { ... }; buy = () => { //... //Logs.latest.push(...) -Как это сделать? this.setState(...) }; render() { return ( <div> ... <button onClick={this.buy}>Купить</button> </div> ) } } //Вывод логов class Logs extends React.Component { state = { latest: [...] } render( <div> {this.state.latest.map((log) => {return (<div>{log.text}</div>)})} </div> ) } 

How can I make it so that when I click on Child.buy () after the purchase an entry is added to the Logs and it is updated?

You can of course store state.latest in Parent and update the array already there. But maybe there is a better solution?

  • one
    There are - redux, mobx and context (React.createContext since version 16.3, although it is not very different from the one you offer). - DiDex
  • There is also an option to put the <Logs /> component into the <Child /> component, I don’t know what logic you have there, but if <Logs /> changes only because of <Child /> then this makes sense. - CoonJS

1 answer 1

if without redux, etc., then the callback function

 class Parent extends React.Component { constructor(props){ super(props); this.state = { item = ""; } } render() { const {item} = this.state; retrun ( <div> <Child change={(item) => this.setState({item: item})}/> <Logs item={item}/> </div> ) } } class Child extends React.Component { state = { ... }; buy = () => { //... //Logs.latest.push(...) -Как это сделать? this.setState(...) this.props.change(...) - сюда то, что нужно передать }; render() { return ( <div> ... <button onClick={this.buy}>Купить</button> </div> ) } } //Вывод логов class Logs extends React.Component { state = { latest: [...] } render( <div> {this.state.latest.map((log) => {return (<div>{log.text}</div>)})} </div> ) } 
  • Writing a function call in the markup of the rendering method is considered to be a sign of poor tone in the reactor. Using the arrow function in the renderer creates a new function each time the component is displayed, which may have performance implications. It will be useful to read this: Arrow Function in Render - Denis Bubnov