将组件作为 props 传递

Passing a component as props

我有一个 class ShowPreview 可以呈现网络摄像头的预览。我正在尝试制作一个 RenderOnClick class 来根据条件呈现组件。

我正在尝试向 RenderOnClick 传递一个 class 将要呈现的内容?我该怎么做?

我这样做是为了不必每次都对条件进行编码。

显示预览

class ShowPreview extends React.Component{
    constructor(props){
        super(props)
    }
    render(){
        return (<QrReader/>)
    }
}

点击渲染

class RenderOnClick extends React.Component{
    constructor(props){
        super(props)
        this.state = ({buttonName: this.props.buttonName, element: this.props.element, isRendered: false})
    }
    render(){
        if(isRendered == false){
            return(<button>{this.state.buttonName}</button>)
        }else{
            return (this.state.element);
        }
    }
}

当你提到将一个组件传递给另一个组件时,我能想到 composition

上面的示例代码link

function SplitPane(props) {
  return (
    <div className="SplitPane">
      <div className="SplitPane-left">
        {props.left}
      </div>
      <div className="SplitPane-right">
        {props.right}
      </div>
    </div>
  );
}

function App() {
  return (
    <SplitPane
      left={
        <Contacts />
      }
      right={
        <Chat />
      } />
  );
}

您可以像 link 中提到的示例那样将组件作为 props 传递,并在您的 RenderOnclick 组件中使用它。

您可以创建一个 higher-order component,它采用您想要有条件地呈现的元素,如下所示:

示例:sandbox

    const RandomElemement = () => <div>Foo!</div>;
    const whenClicked = (WrappedElement) => {
      return class RenderOnClick extends React.Component {
        constructor(props) {
          super(props)
          this.state = ({ 
            buttonName: this.props.buttonName,
            element: this.props.element, 
            isRendered: false })
        }
        handleClick = () => {
          this.setState(prev => ({isRendered: !prev.isRendered}));
        }
        render() {
          const { isRendered } = this.state;
          if (isRendered === false) {
            return (<button onClick={this.handleClick}>{this.state.buttonName}</button>)
          } else {
            return (<WrappedElement />);
          }
        }
      }
    }
    const App = () => {
      const WhenClicked = whenClicked(RandomElemement);
      return (
      <div style={styles}>
        <Hello name="CodeSandbox" />
        <h2>Start editing to see some magic happen {'\u2728'}</h2>
        <WhenClicked buttonName='show foo'/>
        </div>
    )
    };

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