How to update the HelloWorld element from the updateHelloWorld function and in general it is possible?

Code example:

 import * as React from 'react'; import * as ReactDOM from 'react-dom'; import registerServiceWorker from './registerServiceWorker'; function getServerData() { // Получаем данные с сервера data = new GetServerData() return data.data } function updateHelloWorld() { // Магия которая должна обновить элемент } class HelloWorld extends React.Component { render() { return ( <h1>Hello world {getServerData}</h1> ); } } class ButtonClisk extends React.Component { render() { return ( <div> <button onClick={updateHelloWorld}>Обновить</button> </div> ); } } ReactDOM.render( <div> <HelloWorld /> <ButtonClisk /> </div>, document.getElementById('root') as HTMLElement ); registerServiceWorker(); 
  • You can make it easier through setState . But the question is not quite clear what needs to be updated - Denis Bubnov
  • @DenisBubnov update the <HelloWorld /> element and do not update the whole application, that is, without updating <ButtonClisk /> - users
  • Your ButtonClisk ButtonClisk doesn't know anything about the HelloWorld component - this is the first. Secondly, I still do not understand what you want to update there. I think you need to read a little about React and setState . So that you understand how components can interact with each other and how to update them. - Denis Bubnov

1 answer 1

This is possible, but you are not doing it right.

Here is the simplest example of implementation, it is better to read in textbooks in more detail. Try this one or this one for starters, both in Russian.

 // Получаем данные с сервера // допустим, это какой-то сервер или библиотека, которую вы подключаете в своём проекте function getServerData() { return 'SERVER DATA: ' + new Date(); } // это может быть функция, которая вызывается в экшене (если использовать редакс) function updateHelloWorld() { const serverData = getServerData(); console.log('data:', serverData); return serverData; } // первый дочерний компонент class HelloWorld extends React.Component { render() { const data = this.props.data; return ( <div> { data ? data : <h1>Hello world</h1> } </div> ); } } // второй дочерний компонент class ButtonClick extends React.Component { render() { const { onClick } = this.props; return ( <div> <button onClick={onClick}>Обновить</button> </div> ); } } // родительский компонент // он хранит в себе состояние и реагирует на событие/передаёт полученные данные нужному компоненту class App extends React.Component { constructor(props) { super(props); this.state = { data: '' }; this.handleClick = this.handleClick.bind(this); } handleClick() { const data = updateHelloWorld(); this.setState({ data: data }); } render() { const data = this.state.data; return ( <div> {/* данные передаются через пропсы */} <HelloWorld data={data} /> {/* обработчик также передаётся через пропсы */} <ButtonClick onClick={this.handleClick} /> </div> ); } } 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> 

  • Thanks for the answer and for the links to resources, an understanding of the React application architecture has appeared. - users