如何在 React Native Web (Expo) 中使用标签输入

How to have input with label in React Native Web (Expo)

我在 Expo 中使用 React Native Web。我读过它确实可以正确访问,但是我看不到如何为输入添加标签:

  <TextInput
    style={{height: 40, borderColor: 'gray', borderWidth: 1}}
    onChangeText={(text) => this.setState({text})}
    value={this.state.text}
  />

https://reactnative.dev/docs/0.53/textinput

为了澄清并且因为它的名字很奇怪,我使用的是 React Native Web 而不是 React DOM:

https://github.com/necolas/react-native-web

您不需要做任何特别的事情,您可以像处理任何输入一样将 <textInput> 包裹在标签中。

你的代码在一天结束时仍然输出 HTML。

类似的东西(我不知道 React,所以只是用这个作为例子)

import React, { Component } from 'react';
import { AppRegistry, TextInput } from 'react-native';

export default class UselessTextInput extends Component {
  constructor(props) {
    super(props);
    this.state = { text: 'Useless Placeholder' };
  }

  render() {
    return (
    <label>Text Label
      <TextInput
        style={{height: 40, borderColor: 'gray', borderWidth: 1}}
        onChangeText={(text) => this.setState({text})}
        value={this.state.text}
      /></label>
    );
  }
}

// skip this line if using Create React Native App
AppRegistry.registerComponent('AwesomeProject', () => UselessTextInput);

由于您使用的是 React,我认为您不需要支持 Internet Explorer 8 及更低版本,因此将输入包装在标签中将适用于所有屏幕 reader 和浏览器组合。

如果出于任何原因你确实需要支持古老的东西,那么你需要在输入上创建一个 id,这样你就可以在标签上使用 for="itemID"。 (标签上的 for 应包含输入的 id )。请注意,由于 React 的工作方式,您需要将它们包装在 <div> 中。

import React, { Component } from 'react';
import { AppRegistry, TextInput } from 'react-native';

export default class UselessTextInput extends Component {
  constructor(props) {
    super(props);
    this.state = { text: 'Useless Placeholder' };
  }

  render() {
    return (
    <div>
    <label for='itemID'>Text Label</label>
      <TextInput
        style={{height: 40, borderColor: 'gray', borderWidth: 1}}
        onChangeText={(text) => this.setState({text})}
        value={this.state.text}
        id="itemID"
      /></div>
    );
  }
}

// skip this line if using Create React Native App
AppRegistry.registerComponent('AwesomeProject', () => UselessTextInput);

最后,您可以像添加任何其他 属性

一样添加 aria
render() {
    return (
    <label>Text Label
      <TextInput
        style={{height: 40, borderColor: 'gray', borderWidth: 1}}
        onChangeText={(text) => this.setState({text})}
        value={this.state.text}
        aria-labelledby="id(s)OfElement(s)ToLabelThisInput"
      /></label>
    );
  }