如何在渲染内部触发Reactjs onClick而不是返回?

时间:2019-05-27 19:47:50

标签: reactjs onclick

如果我决定在React返回值之外进行条件渲染,该如何分配onClick函数?

Stackoverflow希望我添加比我提供的描述更多的描述,但是我花了1个小时将代码编写到其编辑器中,而没有语法帮助或eslint:D

section:hover {
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"/>

<script type="text/babel">

const RotateOnClick = ( {rotated} ) => {
  if (rotated) {
    return <section>I'M ROTATED! Click me to rotate again!</section>
  } else {
    return <section>I'm not rotated. Click me to rotate!</section>  
  }
}

class Rotator extends React.Component {

  // Change state to true to see that it renders if toggled
  state = {
    isRotated: false
  }
  
  toggleRotation = () => {
    console.log("React doesn't like me. It will never call me :( ")
    const { isRotated } = this.state
    this.setState( {isRotated: !isRotated })
  }
    
  render() {
    const { isRotated } = this.state
    
    let conditionalRender;    
    if (isRotated) {
      conditionalRender = <RotateOnClick rotated onClick={this.toggleRotation} />
    } else {
      conditionalRender = <RotateOnClick onClick={this.toggleRotation} />
    }
  
    return (
    <div className="hover">
      {conditionalRender}
    </div>
    );
  }
}

ReactDOM.render(
    <Rotator />,
    document.getElementById('root')
);
</script>

1 个答案:

答案 0 :(得分:1)

  

<RotateOnClick rotated onClick={this.toggleRotation} />

并不意味着该组件将对click事件做出反应。 您无法将事件处理程序分配给组件!

您应该将处理程序传递给组件,例如

<RotateOnClick rotated clickHandler={this.toggleRotation} />

并在渲染中使用此道具:

const RotateOnClick = ( {rotated, clickHandler} ) => {
  if (rotated) {
    return <section onClick={clickHandler}>I'M ROTATED! Click me to rotate again!</section>
  } else {
    return <section onClick={clickHandler}>I'm not rotated. Click me to rotate!</section>  
  }
}

这种方式的反应应该再好;)