如何从另一个组件的onclick事件触发功能

时间:2019-04-07 15:03:24

标签: reactjs

所以我是ReactJS的新手,如果我正确地解决了他们的测试项目,那么有一家很酷的公司会提供一个初级的React开发人员职位。在项目中,我必须绘制四个svg组件并仅通过一个用户交互(即按钮单击事件)来处理一些简单事件。因此,一切似乎都非常简单,但事实是,我陷入了项目的中间。

我想通过按钮组件中的click事件为其中一个组件提供摇动动画。单击“按钮”时,树应摇动3秒钟,之后将触发另一动作。我准备了一个CSS动画,并且每次单击Button组件时都想更改Tree组件的类。无法找到方法。

这是我的按钮组件

0.3.1

这里是我的Tree组件(它将更改其CSS动画的类名)

class ShakeButton extends React.Component {
    this.props.onClick(this.props.activeClass==='shake')

    render() {
        return (
            <g id="shakeButton" transform="scale(0.15,0.15), translate(3000,-1000)"  onClick={this.handleClick}>
                //a good amount of svg content here
            </g>
        )
    }
}

export default ShakeButton

我将所有组件收集到名为import React, { Components } from "react"; import "./cssTree.css"; class AppleTree extends React.Component{ // state = { // activeClass: '' // } n // handleClick = () => this.props.onClick(this.props.activeClass==='shake') render() { return ( <g className="" id="appleTree" > <g transform="translate(-1000 -1300) scale(1.5)"> //again, some crowded svg content here </g> </g> ) } } export default AppleTree 的组件中,并将其呈现在App.js中

1 个答案:

答案 0 :(得分:0)

您可以尝试抬起onClick method and state up,这意味着将其放在父组件中(我想是App),然后将其传递给子组件。

class App extends React.Component{  
  constructor(props) {
    super(props);
    this.state({
      className: ''
    });
  }
  handleClick = () => {
    this.setState({ className: 'shake' });
  }

  render (
    return (
    // all your components
    <Button clickHandler={this.handleClick} />
    <AppleTree class={this.state.className} />
    )
  )
}

// Button component: Stateless if it doesn't need it's own state
const Button = ({ clickHandler }) => {
 return (
   <g id="shakeButton" transform="scale(0.15,0.15), translate(3000,-1000)"  onClick={() => clickHandler()}>
   //a good amount of svg content here
   </g>
 )
}

// Stateless if it doesn't need its own state
const AppleTree = ({ class }) => {
    return (
      <g className={class} id="appleTree" >
        <g transform="translate(-1000 -1300) scale(1.5)">
         //again, some crowded svg content here
        </g>
      </g>
    )
}


相关问题