如何将this.props数据放入headerRight选择器?

时间:2018-09-26 01:52:43

标签: react-native react-redux react-navigation

我使用react-redux来获取FlatList数据,并使用react-navigation自定义标题。

我想在headerRight中添加选择器,我的问题是我不知道如何将数据添加到headerRight中。

这是我的标题设置。

const data = [
  { key: 0, section: true, label: 'Title' },
  { key: 1, label: 'Red Apples' },
  { key: 2, label: 'Cherries' },
  { key: 3, label: 'Cranberries', accessibilityLabel: 'Tap here for cranberries' },
  { key: 4, label: 'Vegetable', customKey: 'Not a fruit' }
];

class MovieTimeList extends Component {
  static navigationOptions = ({ navigation }) => ({
    title: `${navigation.state.params.theaterCn}`,
    headerStyle: {
      backgroundColor: '#81A3A7', 
      elevation: null,
    },
    headerTitleStyle: {
      fontWeight: '300',
      fontFamily: 'FFF Tusj',
      fontSize: 18
    },
    headerRight:
      <ModalSelector
        data={data}
        initValue="Title"
        onChange={(option)=>{ alert(`${option.label} (${option.key}) nom nom nom`) }}
      />,
  });

这是我的react-redux mapStateToProps函数,该操作被称为API以获取数据:

const mapStateToProps = (state) => {
  const timeList = state.listType.timeList;

  return { timeList };
};

我可以在react-redux中显示movieData中的FlatList

  render() {
    const movieData = this.props.timeList;
    return (
      <View style={{ flex: 1 }}>
        <FlatList
          data={movieData}
          renderItem={this.renderRow}
          horizontal={false}
          keyExtractor={(item, index) => index.toString()}        
        />
      </View>
    );
  }

我不知道如何让const movieData进入我的headerRight选择器。

任何帮助将不胜感激。预先感谢。

2 个答案:

答案 0 :(得分:2)

我不确定此代码是否100%正确,基本上,您可以通过将ur reducer连接到MovieTimeList类并将必要的prop传递到组件来实现

class MovieTimeList extends Component {
  static navigationOptions = ({ navigation }) => ({
    title: `${navigation.state.params.theaterCn}`,
    headerStyle: {
      backgroundColor: '#81A3A7', 
      elevation: null,
    },
    headerTitleStyle: {
      fontWeight: '300',
      fontFamily: 'FFF Tusj',
      fontSize: 18
    },
    headerRight:
      <ModalSelector
        data={data}
        initValue={this.props.HeaderTitle}
        onChange={(option)=>{ alert(`${option.label} (${option.key}) nom nom nom`) }}
      />,
  });


const mapStateToProps = (state) => {
  let HeaderTitle = state.yourreducer.headerTitle
  return HeaderTitle
}

export default connect(mapStateToProps,null)(MovieTimeList)

答案 1 :(得分:1)

您可以设置参数,然后像这样在标题中使用它

 componentWillReceiveProps(nextProp){

   if(!isFetching && listNotUpdated){
      this.props.navigation.setParams({ movieList: nextProp.timeList})
   }
 }

然后像这样在标题中获取

static navigationOptions = ({ navigation }) => {
    const { state } = navigation
    const { movieList }= navigation.state.params
  return {
    title: 'Your Title',
    headerRight: (
      <Button
        title={'Button1'}
        onPress={() => {
          // do something
        }}
      />
    ),
  }

}