我在https://gist.github.com/jesperorb/ad6de7532ade111ae2a7feecc1116339的基础上写了一个试剂 Nose
App.js
import React, { Component } from "react";
import {withToggle} from './withToggle'
export default class App extends Component {
render() {
const ButtonWithToggle = withToggle(<button onClick={()=>{}}>butt</button>);
return (
<div className="App">
<button onClick={()=>{}}>butt</button>
<ButtonWithToggle />
</div>
);
}
}
withToggle.js:
import React, { Component } from "react";
import PropTypes from 'prop-types';
export const withToggle = (ComposedComponent) =>
class extends Component {
static propTypes = {
children: PropTypes.string
}
state = {
toggle: false
}
onClick = () => {
this.setState({ toggle: !this.state.toggle });
}
render() {
return (
<ComposedComponent {...this.props} onClick={this.onClick}>xxx {this.props.children}</ComposedComponent>
)
}
}
因此,我在控制台中收到错误消息:React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object.在 withToggle.js:20 检查你的代码。 (其中 <ComposedComponent
)
可能是什么原因?
最佳答案
HOC 应该应用于组件,而不是渲染组件。
关于你的情况withToggle
适用于 <button onClick={()=>{}}>butt</button>
,这是按钮而不是按钮组件的呈现。
另外,您没有使用 children
是的,你正在覆盖 onClick
由 withToggle
提供与 onClick={()=>{}}
.
试试这个:
App.js
import React, { Component } from "react";
import {withToggle} from './withToggle'
const Button = ({onClick, children}) => <button onClick={onClick}>{children}</button>;
export default class App extends Component {
render() {
const ButtonWithToggle = withToggle(Button);
return (
<div className="App">
<button onClick={()=>{}}>butt</button>
<ButtonWithToggle />
</div>
);
}
}
withToggle.js
import React, { Component } from "react";
import PropTypes from 'prop-types';
export const withToggle = (ComposedComponent) =>
class extends Component {
static propTypes = {
children: PropTypes.string
}
state = {
toggle: false
}
onClick = () => {
this.setState(state => ({ toggle: !state.toggle }));
}
render() {
return (
<ComposedComponent {...this.props} onClick={this.onClick}>{this.props.children}</ComposedComponent>
)
}
}
关于javascript - 带有状态的 React HOC 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51538597/