![](/img/trans.png)
[英]React giving error when used connect function to provide state to Hoc
[英]Error in React HOC with state
我在https://gist.github.com/jesperorb/ad6de7532ade111ae2a7feecc1116339的基础上写了试剂鼻子
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无效 - 期望一个字符串(对于内置组件)或一个类/函数(对于复合组件)但得到:object。 在withToggle.js:20检查您的代码。 (其中<ComposedComponent
)
可能是什么原因?
HOC应该应用于Component而不是渲染组件。
在你的情况下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>
)
}
}
我改变withToggle.js:
import React, { Component } from "react";
import PropTypes from 'prop-types';
export const withToggle = (ComposedComponent) =>
class extends Component {
static propTypes = {
children: PropTypes.string.isRequired,
onClick: PropTypes.func
}
static defaultProps = {
onClick: () => { }
}
state = {
toggle: false
}
onClick = () => {
this.setState({ toggle: !this.state.toggle }, () => console.log('toggle=', this.state.toggle));
this.props.onClick()
}
render() {
console.log('this.props', this.props)
return (
<ComposedComponent {...this.props} onClick={this.onClick}>{this.state.toggle ? 'xxx' : ''}{' '}{this.props.children}</ComposedComponent>
)
}
}
但onClick没有重新定义,按钮内的文字也没有改变((
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.