无状态函数组件不能有引用

Stateless function components cannot hav refs

我正在构建类似于 Facebook 或 instagram 的搜索页面。基本上,如果我们按下搜索按钮,它会导航到 'SearchScreen'。安装其组件后,我想将搜索 header 设置为焦点(光标)。

我的问题是当我将 TextInput ref 设置为道具时。我收到 Stateless function components cannot have refs 错误。这是正确的方法吗?为什么它不起作用?你知道除此之外还有更好的方法吗?

我在 FlatList 的 renderHeader 属性中添加了 _renderHeader 私有函数。 这是 _renderHeader

  _renderHeader = () => {
    return (
      <View style={styles.layoutheader}>
        <View style={styles.containerheader}>
          <RkTextInput
            rkType='row'
            ref="sbar"  /////////////////////HERE////////////
            autoCapitalize='none'
            autoCorrect={false}
            label={<RkText rkType='awesome' style={{color:'white'}}>{FontAwesome.search}</RkText>}
            placeholder='Search'
            underlineWidth="1"
            underlineColor="white"
            style={styles.searchBarheader}
            inputStyle={{color:'white'}}
            labelStyle={{marginRight:0}}
            value={this.state.inputText}
            onChangeText={(inputText)=>{this.setState({inputText})}}
          />
          <View style={styles.left}>
            <RkButton
              rkType='clear'
              style={styles.menuheader}
              onPress={() => {
                this.props.navigation.goBack()
              }}>
              <RkText style={styles.titleText} rkType='awesome hero'>{FontAwesome.chevronLeft}</RkText>
            </RkButton>
          </View>
        </View>
      </View>
    )
  }

componentDidMount() {
    this.refs.sbar.focus(); ////////// Here I want to focus RkTextInput when it's loaded
}

更新 这里是请求的实际代码

class SearchScreen extends Component {
  static navigationOptions = ({navigation}) => ({
    header: null
  })

  state = {
    active: false,
    inputText: ''
  }
   ...
  _renderRow = (row) => {
    ...
    );
  }

  _renderHeader = () => {
    ...
  }

  render() {
    return (
      <FlatList
        data={null}
        renderItem={this._renderRow}
        renderHeader={this._renderHeader}
        keyExtractor={this._keyExtractor}
        ListHeaderComponent={this._renderHeader}
      />
    );
  }

  componentDidMount() {
    this.refs.sbar.focus();
  }
}

在我看来,您没有以正确的方式使用 refs。您使用它们的方式已被弃用。您应该遵循以下语法:

<input
   type="text"
   ref={(input) => { this.textInput = input; }}
 />

当您想访问它时,您可以 this.textInput。在你的情况下,this.textInput.focus().

您正在使用 RkTextInput,它是一个功能组件,不能有引用。这就是为什么你不能集中注意力。

除了包装组件、获取根的引用并找到您的输入元素以聚焦它之外,我看不到聚焦输入的方法。一个粗略的例子:

class RoughExample extends React.Component {
    componentDidMount() {
        //find the input from your root
        this.input = this.root.querySelector('input');
        //if it exists, focus
        this.input && this.input.focus();
    }
    render() {
        <div ref={ (node) => {this.root = node;} }>
            <RkTextInput />
        </div>
    }
}