为了弄清楚我在(未回答的)问题"How do I update a react-bootstrap-table2 cell value after it's edited so a button component in a different column has it?"中解释的问题,我试图传递一个将单元格值返回到按钮组件的函数:
class NominationQueueBootstrapTable extends Component {
...
getInitialBid = (row) => {
console.log('getInitialBid');
return this.state.data.find(r => r.rank === row.rank).initialBid;
}
render() {
const { auctionId } = this.props;
const { teamId } = this.props;
function buttonFormatter(cell, row) {
return (
<NominateButton
row={ row }
auctionId={ auctionId }
teamId={ teamId }
getInitialBid={ this.getInitialBid }
/>
);
}
...
我的NominateButton
组件返回另一个调用包装器的按钮包装器组件:
class NominateButton extends Component {
render() {
const { row } = this.props;
const { auctionId } = this.props;
const { teamId } = this.props;
const playerId = parseInt(this.props.row.player.id, 10);
return (
<Query
query={TEAM_NOMINATIONS_OPEN_QUERY}
variables={{ team_id: teamId }}>
{({ data, loading, error, subscribeToMore }) => {
if (loading) return <Loading />;
if (error) return <Error error={error} />;
return (
<NominateButtonMutator
auctionId={ auctionId }
teamId={ teamId }
playerId={ playerId }
row={ row }
nominationsOpen={ data.team.nominationsOpen }
subscribeToNominationsOpenChanges={ subscribeToMore }
getInitialBid={ this.props.getInitialBid }
/>
);
}}
</Query>
);
}
}
由于我需要在按下按钮时调用转换器,因此我的onClick函数首先调用作为属性传入的getInitialBid函数,然后调用转换器:
class NominateButtonMutator extends Component {
...
handleButtonPressed = (submitBid) => {
this.setState({bidAmount: this.props.getInitialBid(this.props.row)});
submitBid();
};
render() {
const { auctionId } = this.props;
const { teamId } = this.props;
const { playerId } = this.props;
const { nominationsOpen } = this.props;
return (
<Mutation
mutation={SUBMIT_BID_MUTATION}
variables={{
auction_id: auctionId,
team_id: teamId,
player_id: playerId,
bid_amount: this.state.bidAmount
}}
>
{(submitBid, { loading, error }) => (
<div>
<Error error={error} />
<Button
disabled={ loading || !nominationsOpen }
onClick={() => this.handleButtonPressed(submitBid) }
variant="outline-success">
Nominate
</Button>
</div>
)}
</Mutation>
);
}
}
(onClick=
代码已从azium的注释中更新。)
运行此命令时,我得到:
“ TypeError:this.props.getInitialBid不是函数”
这是可行的策略吗?为什么this.props.getInitialBid没有功能?
答案 0 :(得分:1)
您使用的是旧的function
语法,因此this
的绑定不正确。
更改:
function buttonFormatter(cell, row) {
return (
<NominateButton
row={ row }
auctionId={ auctionId }
teamId={ teamId }
// scoped to your local function not your class
getInitialBid={ this.getInitialBid }
/>
);
}
到
const buttonFormatter = (cell, row) => {
return (
<NominateButton
row={ row }
auctionId={ auctionId }
teamId={ teamId }
// this is scoped "lexically" aka to your class
getInitialBid={ this.getInitialBid }
/>
);
}