【问题标题】:how to pass the results of a function from one component to another in react-native?如何在 react-native 中将函数的结果从一个组件传递到另一个组件?
【发布时间】:2018-10-01 20:54:08
【问题描述】:

我有一个运行函数并返回结果的组件,但我需要其他组件才能从函数访问该数据。我怎么能做到这一点?

这是我的 app.js 包含的组件。这是一个示例,但我的问题是如何在 Camera 组件中运行一个函数,然后在 Display 组件中引用数据。

  export default class App extends React.Component {

  render() {
    return (
            <View>
              <Camera />
            </View>
            <View>
              <Display />
            </View>

    );
  }
}

【问题讨论】:

    标签: reactjs react-native components react-props


    【解决方案1】:

    您可以将数据作为状态存储在父组件中,并将其作为道具传递给Display,并允许Camera 通过回调改变状态(下例中的setData)。

    export default class App extends React.Component {
      state = {
        data: null,
      };
      render() {
        return (
          <View>
            <View>
              <Camera setData={(data) => this.setState({ data })} />
            </View>
            <View>
              <Display data={this.state.data} />
            </View>
          </View>
        );
      }
    }
    
    const Camera = props => <Button onPress={() => props.setData(...)} />
    const Display = props => <Text>{props.data}</Text>
    

    【讨论】:

      【解决方案2】:

      如果您的 Display 组件依赖于 Camera 组件数据,我建议您将 Display 组件添加为 Camera 组件中的子组件。 您可以通过以下方式实现:

      • 保持相机组件的状态,
      • 根据某些活动(例如按钮点击)更新函数中的状态
      • 在您的 Camera 组件的 render() 方法中,只有当您的状态中有所需的数据可用时,才挂载 Display 组件。
      • 通过 props 将所需数据传递给 Display 组件。

      例如

      相机组件

      class Camera extends React.Component {
         constructor(props) {
             super(props);
             this.state = {
                 data: null
             }       
          }
      
          foo = () => this.setState({data: 'new_data'});
      
          render() {
               const { data } = this.state;
               const dataPresent = data !== null;
               return (
                {
                   !dataPresent && ( 
                      <button value="set data" onClick={() => this.foo() />                
                )}
                { 
                   dataPresent && ( 
                      <Display data={data} /> 
                )}
              );
      }
      

      }

      显示组件

      const Display = (props) => <div> <span> { props.data } </span> </div>
      

      如果您仍想在另一个组件中传递/使用来自一个组件的数据,并且两个组件处于同一级别,则您需要为父组件提供状态或拥有像 Redux 这样的全局存储 将数据保存在一个地方并在显示组件中访问它。

      【讨论】:

        【解决方案3】:

        我会推荐使用redux,它简化了很多东西,并且不需要升级或将状态传递给父/子

        在您的情况下,您需要在 Camera 和 Display 组件中传递道具

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-10-23
          • 2021-10-18
          • 2018-05-07
          • 2020-12-06
          • 1970-01-01
          • 2017-04-28
          • 2021-10-15
          • 2021-08-11
          相关资源
          最近更新 更多