2017-07-01 55 views
1

我是React的新手,我决定构建一些简单的计算器来练习它的基础知识。然而,我很难理解信息流背后的逻辑,或者有一种方法让子组件执行逻辑并以自然的方式更新父项。使用子组件中的函数更改父组件的状态

例如,这是我的计算器的基本结构:

class Calculator extends React.Component { 
    render() { 
     return (
      <div className="calculator-main"> 
       <Screen numberOnScreen={this.state.numberOnScreen}/> 
        <NumberButton number={7} /> 
        <NumberButton number={8} /> 
        <NumberButton number={9} /> 
        <OperatorButton operator="plus" view="-"/> 
       .... 
      </div> 
     ) 
    } 
} 


class Screen extends React.Component { 
    constructor(props) { 
     super(props); 
    } 

    render() { 
     return (
      <div className="screen">{new Intl.NumberFormat().format(this.props.numberOnScreen)}</div> 
     ); 
    } 
}; 

class NumberButton extends React.Component { 
    constructor(props) { 
     super(props); 
    } 

    render() { 
     const zeroClass = this.props.number === 0 ? " zero" : ""; 
     return (
      <button type="button" className={"number" + zeroClass}>{this.props.number}</button> 
     ); 
    } 
}; 

所以我知道:

  • 我可以创建功能里面计算器,并将它传递为道具,以 按钮组件,并在onClick上调用它。 (但它只是觉得奇怪)。
  • 在Calculator组件中创建一个事件监听器,在按钮组件中创建 函数,并通过事件 触发该值; (但感觉是人造的)。
  • 使用某种全球商店?

但是,有没有自然的反应方式来做到这一点?

谢谢!

+0

你能否详细说明你的意思是 '自然' 是什么?我认为反应的自然方式是将函数从父组件传递给子组件,如以下文章中所述:https://facebook.github.io/react/docs/thinking-in-react.html –

+0

是的,我知道这是React背后的逻辑,但是在父组件中而不是在按钮组件中声明所有我的函数感觉很混乱......所以我的问题基本上是,“就是这样”,你需要工作用这种流程,或者是有一种“反应”的方式来把你的逻辑放在子组件中,并更新父进程的状态。 – Sveta

+1

从技术上讲,你可以使用像redux或flux这样的状态管理库来存储父组件的状态并编写逻辑来改变它在子组件中的状态,所以你不必在父组件中编写任何逻辑。 –

回答

1

我想你想知道关于React组件通信。在这里,我已经实施了从小孩到家长的沟通。

在这种情况下,Parent的状态和状态改变方法通过道具传递给子组件。然后小孩可以改变父母的状态使用这种方法。

React Component Communication

//Parent component 

class Parent extends React.Component{ 
    constructor(props){ 
     super(props); 
     this.state = { 
      content: 'Initial Content' 
     } 
     this.changeContent = this.changeContent.bind(this); 
    } 

    changeContent(event){ 
     this.setState({ 
      content: event.target.value 
     }) 
    } 

    render(){ 
     let { content } = this.state; 
     return <div> 
      <Child content={content} changeContent={this.changeContent}/> 
      <h1>{content}</h1> 
     </div> 
    } 
} 

// Child component 

class Child extends React.Component{ 
    constructor(props){ 
     super(props); 
    } 

    render(){ 
     let { content, changeContent } = this.props; 
     return <input value={content} onChange={changeContent}/> 
    } 
} 
+0

谢谢,以为我提到我知道这个选项:)我只是不喜欢你需要如何实现父内部的逻辑。我想我只能依靠D-reaper建议的依靠redux或类似的库。 – Sveta

+0

这个例子有本地状态。你想将状态转移到redux吗?如果你想将状态移动到redux,我用redux改变我的例子。 – Vasi

相关问题