gpt4 book ai didi

javascript - 带有状态的 React HOC 错误

转载 作者:行者123 更新时间:2023-11-30 11:15:57 25 4
gpt4 key购买 nike

我在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是的,你正在覆盖 onClickwithToggle 提供与 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com