如何在React中与我的无状态组件进行通信?

时间:2017-07-27 12:01:00

标签: reactjs jsx

我想创建一个包含按钮的非常简单的应用。当我点击它时,它应该更改它的名称,并应将其状态更改为:isDisabled:true。我通过编写按钮内联,给它一个OnClick等来实现这一点,但我想尝试使用具有相同功能的无状态组件,但是我完全陷入困境。

import React, { Component } from 'react';
import './App.css';


class App extends Component{
 constructor(){
   super()
   this.state = {name:'Hey buddy click me',
   isDisabled:false,
  }
 }

  render() {
    return (
      <div>
       <MyButton handleClick={this.handleClick.bind(this)}></MyButton>
       </div>
    )
  }
  handleClick = () => {
    this.setState ({
      name:'Dont click!',
      isDisabled:true,
  });

  }
}

const MyButton = (name, isDisabled) => <button onClick={this.handleClick.bind(this)}>{name}</button>

export default App;

1 个答案:

答案 0 :(得分:0)

如果您想要访问name, isDisabled组件,则需要将handleClickMyButton作为道具传递。

虽然名字也可以作为孩子传递。但是,因为我觉得你正在学习开始将它作为props.Then将来可以使用孩子。

import React, { Component } from 'react';
import './App.css';


class App extends Component{
 constructor(){
   super()
   this.state = {name:'Hey buddy click me',
   isDisabled:false,
  }
 }

  render() {
    return (
      <div>
       <MyButton
         name={this.state.name}
         isDisabled={this.state.isDisabled}
         handleClick={this.handleClick.bind(this)}>
       </MyButton>
      </div>
    )
  }
  handleClick = () => {
    this.setState ({
      name:'Dont click!',
      isDisabled:true,
  });

  }
}
//here we need to receive props from parent components, if we need to use here
const MyButton = ({name, isDisabled, handleClick}) => <button onClick={handleClick}>{name}</button>

export default App;
相关问题