Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
945 views
in Technique[技术] by (71.8m points)

reactjs - React-native/react-navigation: how do I access a component's state from `static navigationOptions`?

How do you handle cases when you have, say, a form component, and you need to submit a part of the component's state using button in navigation bar?

const navBtn = (iconName, onPress) => (
  <TouchableOpacity
    onPress={onPress}
    style={styles.iconWrapper}
  >
    <Icon name={iconName} size={cs.iconSize} style={styles.icon} />
  </TouchableOpacity>
)

class ComponentName extends Component {

  static navigationOptions = {
    header: (props) => ({
      tintColor: 'white',
      style: {
        backgroundColor: cs.primaryColor
      },
      left: navBtn('clear', () => props.goBack()),
      right: navBtn('done', () => this.submitForm()), // error: this.submitForm is not a function
    }),
    title: 'Form',
  }

  constructor(props) {
    super(props);
    this.state = {
      formText: ''
    };
  }

  submitForm() {
    this.props.submitFormAction(this.state.formText)
  }

  render() {
    return (
      <View>
        ...form goes here
      </View>
    );
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Simple Design Pattern

Just as a follow-up to @val's excellent answer, here's how I structured my Component so that all the params are set in the componentWillMount. I find this keeps it simpler and is an easy pattern to follow for all other screens.

static navigationOptions = ({navigation, screenProps}) => {
  const params = navigation.state.params || {};

  return {
    title:       params.title,
    headerLeft:  params.headerLeft,
    headerRight: params.headerRight,
  }
}

_setNavigationParams() {
  let title       = 'Form';
  let headerLeft  = <Button onPress={this._clearForm.bind(this)} />;
  let headerRight = <Button onPress={this._submitForm.bind(this)} />;

  this.props.navigation.setParams({ 
    title,
    headerLeft,
    headerRight, 
  });
}

componentWillMount() {
  this._setNavigationParams();
}

_clearForm() {
  // Clear form code...
}

_submitForm() {
  // Submit form code...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...