我们可以将 setState 作为 props 从一个组件传递到另一个组件并在 React 中从子组件更改父状态吗? [英] Can we pass setState as props from one component to other and change parent state from child component in React?

查看:45
本文介绍了我们可以将 setState 作为 props 从一个组件传递到另一个组件并在 React 中从子组件更改父状态吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 class App extends Component {构造函数(){极好的();this.state = {名称:'反应'};this.setState=this.setState.bind(this)}使成为() {返回 (<div><Hello name={this.state.name}/><p>开始编辑以看到一些奇迹发生:)</p><孩子{...this}/>

);}}子组件var Child=(self)=>{返回(<button onClick={()=>{自我 .setState({名称:"viswa"})}}>点击</button>)

这里我绑定了 setState 函数并将其作为道具发送给子组件.这会改变父组件的状态.这是正确的方法吗?

解决方案

但这比传递函数简单.如果我想改变很多状态改变.与传递函数相比,这将是简单快捷的方法,对吗?

执行此操作的正确方法与您的方法一样简单,并且不会违反最佳做法:

class App 扩展组件 {状态 = {name: '反应',};使成为() {返回 (<div><Hello name={this.state.name}/><p>开始编辑以看到一些奇迹发生:)</p><Child onClick={() =>this.setState({name: 'viswa'})}/>

);}}const Child=({onClick})=>(<button onClick={onClick}>点击</button>);

 class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React'
    };
    this.setState=this.setState.bind(this)
  }

  render() {
    return (
      <div>
        <Hello name={this.state.name} />
        <p>
          Start editing to see some magic happen :)
        </p>
        <Child {...this}/>
      </div>
    );
  }
}

child Component
var Child=(self)=>{
  return(
    <button  onClick={()=>{
      self .setState({
        name:"viswa"
      })
    }}>Click </button>
  )

here I am binding the setState function and send this as props to child component.This will change state of parent from child.Is this proper way?

解决方案

But this is simple than passing function.If I want change many state change. this will be simple and faster way compare to passing function right ?

The correct way to do this is as simple as yours and does not violate best practices:

class App extends Component {
  state = {
      name: 'React',
  };

  render() {
    return (
      <div>
        <Hello name={this.state.name} />
        <p>
          Start editing to see some magic happen :)
        </p>
        <Child onClick={() => this.setState({name: 'viswa'})}/>
      </div>
    );
  }
}

const Child=({onClick})=>(
    <button onClick={onClick}>Click</button>
);

这篇关于我们可以将 setState 作为 props 从一个组件传递到另一个组件并在 React 中从子组件更改父状态吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆