React-Native React-Navigation 标题按钮 testID

P.L*_*and 5 react-native react-navigation

有没有一种方法可以将 testID 和accessibilityLabel 添加到标题按钮(例如标题后退按钮),以便能够编写自动化测试?

And*_*rew 6

根据您如何设置标题中的按钮将取决于您如何设置 testID 等。

返回键

对于<Back按钮。它使用了accessibilityLabel附带的组件HeaderBackButton.jsx,accessibilityRole集,你可以在这里看到。

accessibilityRole="button"
accessibilityLabel={accessibilityLabel}
testID={testID}
Run Code Online (Sandbox Code Playgroud)

在创建后退按钮的函数签名中,您可以设置accessibilityLabel和 ,testID 您可以在此处看到。这是默认值accessibilityLabel

accessibilityLabel = label && label !== 'Back' ? `${label}, back` : 'Go back',
Run Code Online (Sandbox Code Playgroud)

React-Native 按钮

如果您使用的<Button />是react-native 中的组件,您只需传递您想要的testID 和accessibilityLabel 即可。

static navigationOptions = {
  headerTitle: 'Title',
  headerRight: (
    <Button
      onPress={() => alert('This is a button!')}
      title="Right"
      color="#000"
      testID='headerRightButton'
      accessibilityLabel="Right button!"
    />
  ),
  headerLeft: (
    <Button
      onPress={() => alert('This is a button!')}
      title="Left"
      color="#000"
      testID='headerLeftButton'
      accessibilityLabel="Left button!"
    />
  )
};
Run Code Online (Sandbox Code Playgroud)

#你自己的按钮 如果你创建了自己的按钮来使用,那么你必须自己处理这些按钮并将道具传递到组件的可触摸部分,请参阅文档以获取更多信息https://facebook.github.io/反应本机/文档/accessibility#accessibilitylabel-ios-android

这是您可以执行的操作的基本示例

class MyButton extends Component {
  render() {
    return (
      <TouchableOpacity onPress={() => {}}
       testID={this.props.testID}
       accessibilityLabel={this.props.accessibilityLabel}
      >
        <View>  
         // style your awesome button here
        </View>
      </TouchableOpacity>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以这样称呼

<MyButton
 testID={'mybutton'}
 accessibilityLabel={'tap my button'} />
Run Code Online (Sandbox Code Playgroud)

您可以/应该在 testID 等上设置 prop 默认值