javascript - 将方法作为 prop 传递给类静态函数

标签 javascript react-native

我自己无法解决这个问题。我有一个类(class)

class WebViewScreen extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      url: 'https://example.org',
    };
  }
  
  someMethod = () => {
    return 'something';
  }

  render() {
    return (
      <View style={styles.mainContainer}>
        <WebView
          source={{uri: this.state.url}}
        />
        <StatusBar backgroundColor="white" barStyle="dark-content" />
      </View>
    );
  }
  static navigationOptions = ({navigation}) => {
    return {
      headerTitle: () => (
        <AddressBar navigation={navigation} />
      ),
    };
  };
}

我想从static navigationOptions访问someMethod

<小时/>

我尝试了以下方法但没有成功:

运行this.someMethod()

运行WebViewScreen.someMethod()

let _this 在类之外,然后在 WebViewScreen 类构造函数中 _this = this 然后来自 static navigationOptions

_this.someMethod() <小时/>

我的问题是,我怎样才能实现这一目标?

最佳答案

您无法从静态方法中访问组件的状态。您可以做的就是保持导航参数与本地状态同步和/或将函数传递给它

this.props.navigation.setParams({
  someMethod: this.someMethod.bind(this)
})

您可以通过以下方式检索:

static navigationOptions = ({ navigation }) => {
  const someMethod = navigation.getParam('someMethod', () => null)
  // ... someMethod()

关于javascript - 将方法作为 prop 传递给类静态函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59213194/

相关文章:

php - 选中复选框时隐藏表格行

javascript - 当用户单击提交按钮时,我想将对象类型转换为 j-son 以在 rest api 中发布数据

swift - 是否可以将应用程序中的图像分享到 Instagram Story

Javascript setTimeout 立即在 React Native 中运行

javascript - react native : Can't see changes to my code

android - React Native ScrollView 在 Android Landscape 上裁剪最后一个元素

javascript - 如何使用 .every() 方法验证针对 Regex 的输入?

javascript - 在主干/下划线模板中使用循环

javascript - 根据 ng-grid selectedItem[0] 更改下拉选项

javascript - 在两个可拖动的 Flatlist-React Native 之间拖放