首页 > 解决方案 > 如何在 React 中使用类组件之外的函数

问题描述

我想了解反应中的功能组件,但没有得到真实的图片。在这里,我拿了一些代码并对其进行了修改以供自己理解。任何帮助。

反应:

class App extends React.Component {
    state = { count: 0, add: 2 }

    handleIncrement() {
      this.setState({ count: this.state.count + 1 })
    }

    handleDecrement() {
       this.setState({ count: this.state.count - 1 })
     }

     anyMore() {
        this.setState({ add: this.state.add })
        this.setState({ count: this.state.count })
        any(add, count)
     }

    render() {
       return (
         <div>
             <button onClick={this.handleIncrement}>Increment by 1</button>
             <button onClick={this.handleDecrement}>Decrement by 1</button> <br />
             <button onClick={this.anyMore}>Add 2</button>
             <div>
                <p>&nbsp;{this.state.count} </p> <p>&nbsp; {this.state.add} </p>
             </div>
         </div>
    )
  }
}

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

  function any() {
     return a * b;
   }  

标签: javascriptreactjs

解决方案


只是想了解并找出解决方案,我认为您可以这样做

class App extends Component {

render() {
    return (
        Any()
    );
}
}
const Any = () => {
return (
    <div>
        return a * b
    </div>
);
};

export default App;

推荐阅读