我试图从React 16.2中的无状态功能组件中提取业务逻辑。
这有效:
const Jobs = props => (
props.entries
.map(entry => (
<Job
entry={entry}
isInitJobExpanded={
entry.fields.project['en-US'] &&
props.initJobExpanded &&
(entry.fields.project['en-US'] === props.initJobExpanded)}
key={entry.sys.id}
/>
)));
当我想要提取isInitJobExpanded
时,我已尝试过:
const isInitJobExpandedFunction = ({ entry, props }) => (
entry.fields.project['en-US'] &&
props.initJobExpanded &&
entry.fields.project['en-US'] === props.initJobExpanded
);
const Jobs = props => (
props
.map(entry => (
<Job
entry={entry}
isInitJobExpanded={isInitJobExpandedFunction}
key={entry.sys.id}
/>
)));
但是,我收到错误消息:
Invalid prop `isInitJobExpanded` of type `function` supplied to `Job`, expected `boolean`.`
我也尝试过:
isInitJobExpanded={this.isInitJobExpandedFunction}
isInitJobExpanded={this.isInitJobExpandedFunction()}
isInitJobExpanded={isInitJobExpandedFunction()}
isInitJobExpanded={() => isInitJobExpandedFunction}
等
提前致谢。
答案 0 :(得分:1)
isInitJobExpandedFunction
会收到一个对象,该对象必须包含两个字段:entry
和props
。所以你的代码是:
const isInitJobExpandedFunction = ({ entry, props }) => (
entry.fields.project['en-US'] &&
props.initJobExpanded &&
entry.fields.project['en-US'] === props.initJobExpanded
);
const Jobs = props => (
props
.map(entry => (
<Job
entry={entry}
isInitJobExpanded={isInitJobExpandedFunction({entry, props})}
key={entry.sys.id}
/>
)));