javascript - 在 React-Native Navigator 中传递 props/state

标签 javascript reactjs react-native react-native-router-flux

这里是 React Native 新手。

我正在尝试构建一个简单的 React Native 应用程序来进行练习,它本质上只是一个多页联系表单。

当我通过导航器(navigatorRenderScene 函数)渲染子组件时,我无法找出将 Prop /状态传递给子组件的最佳方法

每当我尝试在这里为我的组件分配 props 时,它都允许我传递字符串,但不能传递函数或对象。例如,在组件 First 中,我尝试传递一个字符串和一个函数。页面呈现后,只有字符串才会保留其值。

我这样做完全是错误的吗?我是否需要研究某种状态管理系统,例如 Flux 或 Redux?甚至可能是 redux 路由器包? (说实话,还没接触过这些)

路由一切正常,只是我无法弄清楚 Prop /状态。

这是我的索引

import React, { Component } from 'react';
import {
  AppRegistry,
  Navigator,
  StyleSheet,
  Text,
  View,
  TouchableHighlight
} from 'react-native';

import { Container, Header, Title, Content, List, ListItem, InputGroup, Input, Button, Icon, Picker } from 'native-base'

// a bunch of crap here being imported that I don't need, I'll trim it down later.

import First from './components/First'
import Second from './components/Second'

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      text : 'initial state',
      sentBy : '',
      company : '',
      phoneNumber : ''
    };
    this.testFunc = this.testFunc.bind(this)
  }
  // end constructor

  mostRecentPush() {
    // firebase stuff, not really important to the problem
    console.log('pushing input data to DB')
    firebase.database().ref('mostRecent/').set({
      'body' : this.state.text,
      'sentBy' : this.state.sentBy,
      'location' : this.state.pickerValue,
      'company' : this.state.company
    });

    firebase.database().ref('emails/').push({
      'body' : this.state.text,
      'sentBy' : this.state.sentBy,
      'location' : this.state.pickerValue,
      'company' : this.state.company
    })
  }
  // end mostRecentPush() / firebase stuff

  onButtonPress() {
    this.props.navigator.push({
      id: 'Second'
    })
  } // end onButtonPress

  testFunc() {
    console.log('calling this from the index')
  }

  render() {
    console.log('rendering home')
    return (
        <Navigator
          initialRoute = {{
            id: 'First'
          }}
          renderScene={
            this.navigatorRenderScene
          }
         />
      )
  } // end render

  navigatorRenderScene(route, navigator) {
    _navigator = navigator;  
    switch (route.id){
      case 'First':
        return(<First testString="cat123" testFunc={this.testFunc} navigator={navigator} title="First" />)
        // passing our navigator value as props so that the component has access to it
      case 'Second':
        return(<Second navigator={navigator} title="Second" />)
      case 'Third':
        return(<Third navigator={navigator} title="Third" />)
      case 'Fourth':
        return(<Fourth navigator={navigator} title="Fourth" />)
      case 'Fifth':
        return(<Fifth navigator={navigator} title="Fifth" />)
    } //end switch
  } // end navigatorRenderScene
} // end component

AppRegistry.registerComponent('App', () => App);

这是一个示例组件,First

import React, { Component } from 'react';
import {
  AppRegistry,
  Navigator,
  StyleSheet,
  Text,
  View,
  TouchableHighlight
} from 'react-native';

import { Container, Header, Title, Content, List, ListItem, InputGroup, Input, Button, Icon, Picker } from 'native-base'

// too much stuff being imported, will clean this up later

class First extends Component {

  constructor(props) {
    super(props)
    this.onButtonPress = this.onButtonPress.bind(this)
  }

  onButtonPress() {
    this.setState({
      text: 'changed state from first component'
    })

    console.log(this.state)

    this.props.navigator.push({
      id: 'Second'
    })
  }

  render() {
    return(
        <Container>
         {console.log('rendering first')}
            <Content>
                <List>
                    <ListItem>
                        <InputGroup>
                            <Input 
                              placeholder='Name' 
                            />
                        </InputGroup>
                    </ListItem>
               </List>
                <TouchableHighlight onPress={this.onButtonPress}>
                  <Text>Go to Page 2</Text>
                </TouchableHighlight>
            </Content>
        </Container>
      )
  }
}


export default First

最佳答案

我认为问题在于范围。将 renderScene 属性设置为导航器时,您没有将该函数绑定(bind)到实际的类,因此当执行 navigatorRenderScene 时,它​​的作用域与 testFunc 不同。

尝试更改这行代码:

navigatorRenderScene(route, navigator) {
  //...
}

为此:

navigatorRenderScene = (route, navigator) => {
  // ...
}

箭头函数会将 navigatorRenderScene 绑定(bind)到该类,因此 this.testFunc 将存在于该类中。

进行绑定(bind)的其他选项

如果您不想使用箭头函数,您可以在构造函数中尝试类似的操作。

// First options
this.navigatorRenderScene = this.navigatorRenderScene.bind(this)

或者您也可以直接在回调上使用bind方法

// Second option
renderScene={
  this.navigatorRenderScene.bind(this)
}

或者箭头函数

// Third option
renderScene={
  (route, navigator) => this.navigatorRenderScene(route, navigator)
}

请告诉我这是否有效。祝你好运!

关于javascript - 在 React-Native Navigator 中传递 props/state,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40034617/

相关文章:

javascript - 打开后拒绝错误 `.catch`

javascript - 浏览器端 javascript markdown 适合服务器端 upskirt

reactjs - 如何使用 formdata 将图像文件发送到 React/Next js api?

javascript - 如何阻止文本中的脚本标签执行?

javascript - 我怎样才能使这段代码更好地工作?

reactjs - 使用Nginx部署React加载资源失败

android - 哪种 JavaScript 框架最适合移动应用程序开发

ios - 找不到 'glog/logging.h'文件怎么解决

css - React Native 中的重叠元素样式?

react-native - 无效或意外的 token ,测试裸 react native 应用程序