javascript - 父组件如何在 React 中改变子组件的 props?

标签 javascript reactjs ecmascript-6

我是个新手,对某些事情有点困惑。我在网上读过很多文章,声称组件无法更改其自己的 props,但父组件可以更改其子组件的 props。但是,我还没有看到任何实际说明如何做到这一点的内容。

我希望能够做到这一点:

class Parent extends Component {
  constructor(props) {
    super(props);
    this.childProps = {name:'name',age:12,type:'child'}; 
    this.changeChild = this.changeChild.bind(this);
  }

  changeChildName(newName) {
    //change prop 'name' of child here;
  }

  render() {
    return (
      <Child {...this.childProps} />
    );
  }
}

但是,我根本不知道如何做到这一点 - 尽管我读过的几乎所有关于 React 的 Material 都说父级可以更改其子级的 props。我可以正常工作的内容如下:

class Parent extends Component {
  constructor(props) {
    super(props);
    this.state = {name:'name',age:12,type:'child'}; 
    this.changeChild = this.changeChild.bind(this);
  }

  changeChildName(newName) {
    this.setState({name: newName});
  }

  render() {
    return (
      <Child {...this.state} />
    );
  }
}

当我唯一想要重新渲染的是 subview 时,父级需要重新渲染对我来说似乎有点过分了。如何更改<Child>的 Prop 来自 <Parent> 的组件成分?

次要问题

1)是否可以在不重新渲染组件的情况下更改组件的状态?

2) 有没有onStateChange输入我们可以利用的事件,或者我们只有 componentWillReceiveProps

最佳答案

1) Is it possible to change the state of a component without having the component re-render?

不,这没有什么意义。

2) Is there an onStateChange type event that we can tap into, or do we solely have componentWillReceiveProps?

没有,使用componentWillReceiveProps

It seems a bit overkill to me that the Parent needs to re-render when the only thing that I want to re-render is the child view.

实际上,这就是你欺骗自己的地方:父级已更改,因为它返回的内容已更改。整棵树从根开始重新渲染。

关于javascript - 父组件如何在 React 中改变子组件的 props?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40777002/

相关文章:

javascript - 从 getInitialState 渲染一次,然后在 componentDidMount 之后再次渲染

reactjs - 使用 Mocha/Chai 测试复杂的 React 组件

reactjs - react 导航:useFocusEffect 不是函数

javascript - Es6 React 组件引用

javascript - localstorage key本身占用多少空间?

javascript - 根据页面加载时的下拉值显示隐藏/div

javascript - 检查给定的 DOM 元素是否已准备好

c# - 在客户端上显示服务器日期和服务器时间

javascript - 响应中的“Access-Control-Allow-Credentials” header 为 '',必须为 'true'

JavaScript 幻灯片放映不流畅