@dc65k

Как в React передать в hoc стрелочную функцию?

Есть пример, в нём всё корректно работает:
https://codepen.io/dc65k/pen/YzGNdap

import React, { Component, PureComponent } from 'react';
import './App.css';

class Twitter extends PureComponent {

  state = {
    todos: null
  }

  async componentDidMount() {
    const response = await fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(response => response.json());

    this.setState({
      todos: response
    });
  }

  render() {

    const {
      children
    } = this.props;

    const {
      todos
    } = this.state;

    return (
      <React.Fragment>
        {
          React.cloneElement(children, { ...this.state })
        }
      </React.Fragment>
    )
  }
}

const UserProfile = (props) => {
  const { todos } = props;

  return (
    <React.Fragment>
      {
        todos ? <h2>UserProfile</h2> : <div>Loading...</div>
      }
    </React.Fragment>
  )
}

class App extends Component {
  render() {
    return (
      <div className="App">
        <Twitter username='user1'>
          {/* {
            (props) => {
              return (
                <h2>UserProfile</h2>
              )
            }
          } */}
          <UserProfile />
        </Twitter>
      </div>
    );
  }
}
export default App;

Во втором примере я передаю не компонент, а стрелочную функцию, и данный пример уже не работает:

import React, { Component, PureComponent } from 'react';
import './App.css';

class Twitter extends PureComponent {

  state = {
    todos: null
  }

  async componentDidMount() {
    const response = await fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(response => response.json());

    this.setState({
      todos: response
    });

  }

  render() {
    const {
      children
    } = this.props;

    const {
      todos
    } = this.state;

    return (
      <React.Fragment>
        {
          React.cloneElement(children, { ...this.state })
        }
      </React.Fragment>
    )
  }
}

const UserProfile = (props) => {
  const { todos } = props;

  return (
    <React.Fragment>
      {
        todos ? <h2>UserProfile</h2> : <div>Loading...</div>
      }
    </React.Fragment>
  )
}

class App extends Component {
  render() {
    return (
      <div className="App">
        <Twitter username='user1'>
          {
            (props) => {
              return (
                <h2>UserProfile</h2>
              )
            }
          }
          {/* <UserProfile /> */}
        </Twitter>
      </div>
    );
  }
}
export default App;

Как во втором примере сделать правильно?
  • Вопрос задан
  • 79 просмотров
Решения вопроса 1
Krasnodar_etc
@Krasnodar_etc
fundraiseup
а, я наконец понял, что именно вы хотите сделать. Функции нельзя передать в children, получите ошибку Functions are not valid as a React child. Тут два варианта:
1 - Передавать в children компонент, как в первом примере
2 - Уйти от children в пользу передачи контента через функцию

Условно
class App extends Component {
  render() {
    const renderContent = params => { params.todos ? <h2>UserProfile</h2> : <div>Loading...</div> }

    return (
      <div className="App">
        <Twitter username='user1' renderContent={ renderContent } />
      </div>
    );
  }
}

Ну, и класс Twitter немножко дописать, в таком варианте он должен рендерить результат renderContent(this.state) , а не children

Edit: первый ответ был не верный, обновил
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы