理解 ReactElement proptype
Understanding ReactElement proptype
我正在研究 material-ui
以了解 React。我想知道为什么会收到以下错误消息:
Invalid prop 'rightIconButton' of type 'function' supplied to 'ListItem', expected a single ReactElement.
当我使用无状态组件时它工作得很好,但是如果我需要有状态组件或者我需要访问 props
对象怎么办。
正确的做法是什么?
class ParticipantList extends Component {
render() {
return (
<List>
{this.props.participants.map(function(participant){
return (
<ListItem key={participant._id}
primaryText={participant.fullname()}
rightIconButton={participant.needHelp ? rightIconMenu : null}
/>);
})}
</List>
);
}
}
class rightIconMenu extends Component {
render(){
return (
<IconMenu iconButtonElement={menuIconButton}>
<MenuItem>Action</MenuItem>
</IconMenu>
);
}
};
const menuIconButton = (
<IconButton
touch={true}
tooltip="more"
tooltipPosition="bottom-left"
>
<ActionGrade color={pinkA200} />
</IconButton>
);
对象 rightIconMenu
是一个 class。在 JavaScript 领域,class 本质上是一个 JavaScript 函数,有时,它是 字面上的 一个 JavaScript 函数(即是,如果你正在编译 ES6/ES2015/ES.next to ES5).
因此错误消息显示为 'rightIconButton' of type 'function' supplied to 'ListItem'
。标识符 rightIconButton
表示未初始化的 class,如果您还记得的话,它本质上是一个函数。根据 ListItem
的定义,rightIconButton
必须 是 React 元素,而不是其他任何东西,无论是字符串、数字还是函数。
在 React 中,抑制此错误的一种方法是使用以下语法实际初始化所述 class(在语义上表示组件):
<rightIconButton />
{/* Just be sure to supply any necessary props */}
此外,根据 ListItem
组件中定义的 PropType,仔细检查库以确认 rightIconButton
是否可选。如果它不是可选的,那么 null
可能同样会引发错误。幸运的是,解决方法可能只是提供一个空的 span
,如下所示:
rightIconButton={participant.needHelp ? <rightIconMenu /> : <span />}
我正在研究 material-ui
以了解 React。我想知道为什么会收到以下错误消息:
Invalid prop 'rightIconButton' of type 'function' supplied to 'ListItem', expected a single ReactElement.
当我使用无状态组件时它工作得很好,但是如果我需要有状态组件或者我需要访问 props
对象怎么办。
正确的做法是什么?
class ParticipantList extends Component {
render() {
return (
<List>
{this.props.participants.map(function(participant){
return (
<ListItem key={participant._id}
primaryText={participant.fullname()}
rightIconButton={participant.needHelp ? rightIconMenu : null}
/>);
})}
</List>
);
}
}
class rightIconMenu extends Component {
render(){
return (
<IconMenu iconButtonElement={menuIconButton}>
<MenuItem>Action</MenuItem>
</IconMenu>
);
}
};
const menuIconButton = (
<IconButton
touch={true}
tooltip="more"
tooltipPosition="bottom-left"
>
<ActionGrade color={pinkA200} />
</IconButton>
);
对象 rightIconMenu
是一个 class。在 JavaScript 领域,class 本质上是一个 JavaScript 函数,有时,它是 字面上的 一个 JavaScript 函数(即是,如果你正在编译 ES6/ES2015/ES.next to ES5).
因此错误消息显示为 'rightIconButton' of type 'function' supplied to 'ListItem'
。标识符 rightIconButton
表示未初始化的 class,如果您还记得的话,它本质上是一个函数。根据 ListItem
的定义,rightIconButton
必须 是 React 元素,而不是其他任何东西,无论是字符串、数字还是函数。
在 React 中,抑制此错误的一种方法是使用以下语法实际初始化所述 class(在语义上表示组件):
<rightIconButton />
{/* Just be sure to supply any necessary props */}
此外,根据 ListItem
组件中定义的 PropType,仔细检查库以确认 rightIconButton
是否可选。如果它不是可选的,那么 null
可能同样会引发错误。幸运的是,解决方法可能只是提供一个空的 span
,如下所示:
rightIconButton={participant.needHelp ? <rightIconMenu /> : <span />}