【发布时间】:2019-07-03 08:24:59
【问题描述】:
这可行,但我需要分离出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。如果我点击“no.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 中的一个组件,我无法覆盖库代码。还有其他方法吗?
【问题讨论】:
-
您可以只使用无状态的功能组件的组件语法:
<CellRenderer />,然后以传统方式传入 props。此外,如果没有参数,那么只需将函数本身作为道具传递,而不是调用它的匿名函数,例如将onClick={() => this.handleIncrement()}更改为简单的onClick={this.handleIncrement} -
如果您使用
react-window并且需要将道具传递给渲染器,请查看itemData道具,因为这可能会为您提供所需的东西(react-window.now.sh/#/api/FixedSizeList)。如果这不能满足您的需求,React context API 可能会派上用场