React JS-使用HOC时发生不变违规错误

时间:2019-06-26 10:38:51

标签: reactjs jsx

在学习react的高阶组件时,我试图在我的代码中使用它。这样做时,我收到“不变违规错误”

//Higher Order Component
const withStyles = (OriginalComponent) => {
  class NewComponent extends React.Component{
    render(){
      return <OriginalComponent />  
    }
  }
  return NewComponent;
}

class FancyButton extends React.Component {
  render() {
    return <button>Fancy button</button>;
  }
}


const App = props => {
//I am calling the HOC to get my updated component
  let Enhanced = withStyles(<FancyButton />);

  return (
      <Enhanced />
  );
};

ReactDOM.render(<App />, document.getElementById("root"));

在这里,我正在调用HOC(withStyles),并将返回的组件存储在变量“ Enhanced”中。在App组件中,我可以直接调用增强型组件吗?

我希望输出应该是按钮元素,但是出现“ Invariant Violation”错误

1 个答案:

答案 0 :(得分:0)

您正在传递FancyButton的渲染结果,而您应该传递实际的组件功能 见下文:

...
const App = props => {
//I am calling the HOC to get my updated component
  let Enhanced = withStyles(FancyButton);

  return (
      <Enhanced />
  );
};
...