Передача реквизитов в функцию как дочерний компонент - PullRequest
0 голосов
/ 09 февраля 2019

Это работает, но мне нужно выделить компонент cellRenderer.

// Grid.js
import React, { Component } from "react";

class Grid extends Component {
  render() {
    const index = 3;
    return (
      <div style={{ height: "5em", width: "6em", border: "1px solid black" }}>
        {this.props.text}
        {this.props.children({ index, cellText: "no." })}
      </div>
    );
  }
}

export default Grid;

И App.js.Если я нажимаю «№ 3», он корректно записывает «x: 6»

import React, { Component } from "react";
import Grid from "./Grid";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      x: 5
    };
  }

  handleIncrement = () => {
    this.setState(
      state => ({ x: state.x + 1 }),
      () => console.log(`x: ${this.state.x}`)
    );
  };

  cellRenderer = ({ index, cellText }) => {
    return <div onClick={() => this.handleIncrement()}>{cellText + index}</div>;
  };

  render() {
    return (
      <div className="App">
        <Grid text={"Hello "}>{this.cellRenderer}</Grid>
      </div>
    );
  }
}

export default App;

Теперь, если мне нужно выделить cellRenderer компонент, как показано ниже, как я могу передать handleIncrementфункция к этому?

import React, { Component } from "react";
import Grid from "./Grid";

const cellRenderer = ({ index, cellText }) => {
  return <div>{cellText + index}</div>;
};

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      x: 5
    };
  }

  handleIncrement = () => {
    this.setState(
      state => ({ x: state.x + 1 }),
      () => console.log(`x: ${this.state.x}`)
    );
  };

  render() {
    return (
      <div className="App">
        <Grid text={"Hello "}>{cellRenderer}</Grid>
      </div>
    );
  }
}

Редактировать:

Это работает:

// pass handleIncrement to Grid
<Grid text={"Hello "} handleIncrement={this.handleIncrement} >{cellRenderer}</Grid>

// And within Grid, pass it to cellRenderer
{this.props.children({ index, cellText: "no.", handleIncrement: this.props.handleIncrement })}

// Update cellRenderer to this
const cellRenderer = ({ index, cellText, handleIncrement }) => {
    return <div onClick={handleIncrement}>{cellText + index}</div>;
};

Но проблема в том, что Grid является компонентом из библиотеки react-window, и я не могу переопределить код библиотеки.Возможен ли другой способ?

Ответы [ 2 ]

0 голосов
/ 09 февраля 2019

Это будет работать:

import React, { Component } from 'react'
import Grid from './components/Grid'

const CellRenderer = ({ index, cellText, handleIncrement }) => {
  return <div onClick={handleIncrement}>{cellText + index}</div>
}

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      x: 5
    }
  }

  handleIncrement = () => {
    this.setState(
      state => ({ x: state.x + 1 }),
      () => console.log(`x: ${this.state.x}`)
    )
  }

  render() {
    return (
      <div className="App">
        <Grid text={'Hello '}>
          {props => (
            <CellRenderer {...props} handleIncrement={this.handleIncrement} />
          )}
        </Grid>
      </div>
    )
  }
}

export default App
0 голосов
/ 09 февраля 2019

Тот факт, что вы выделили наш cellRenderer как функциональный компонент, вы можете сделать его как компонент и передать реквизиты

const CellRenderer = ({ index, cellText, handleIncrement }) => {
  return <div onClick={handleIncrement}>{cellText + index}</div>;
};
...

return (
      <div className="App">
        <Grid text={"Hello "}>{({index, cellText}) => <CellRenderer handleIncrement={this.handleIncrement} index={index} cellText={cellText}/>}</Grid>
      </div>
    );
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...