Javascript 在自定义组件中响应本机访问引用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36716207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:28:19  来源:igfitidea点击:

React native accessing refs in a custom component

javascriptreact-nativeecmascript-6

提问by prinnny

I have a custom TextInput. When I edit the first TextInputand hit the "Next" in the keyboard, I want it to focus the second TextInput. I have searched before in Stack Overflow and it seems I can do it using ref. However I'm not sure how to do that with custom TextInput.

我有一个自定义的 TextInput。当我编辑第一个TextInput并点击键盘上的“下一步”时,我希望它关注第二个TextInput. 我之前在 Stack Overflow 中搜索过,似乎我可以使用ref. 但是我不确定如何使用 custom 来做到这一点TextInput

Here is my basic CustomTextInput code:

这是我的基本 CustomTextInput 代码:

let CustomTextInput = React.createClass({
    propTypes: {
        refName: React.PropTypes.string,
        returnKeyType: React.PropTypes.string,
        onSubmitEditing: React.PropTypes.func
    },

    getDefaultProps: function(){
        return {
            refName: "",
            returnKeyType: "default",
            onSubmitEditing: () => {}
        }
    },

    render: function(){
        return(
            <View>
                <TextInput 
                    ref={this.props.refName}
                    returnKeyType={this.props.returnKeyType}
                    onSubmitEditing={this.props.onSubmitEditing}
                />
            </View>
        )
    }
});

module.exports = CustomTextInput

And here is my Parent class that calls it:

这是我的父类调用它:

let MyParent = React.createClass({
    render: function(){
        return(
            <View>
                <CustomTextInput
                    refName={'firstNameInput'},
                    returnKeyType={'next'}
                    onSubmitEditing={(event) => { 
                        this.refs.lastNameInput.focus();
                    }}
                />
                <CustomTextInput
                    refName={'lastNameInput'}
                />
            </View>
        )
    }
});

Right now, when I press the Nextin the keyboard, after selecting the firstName, I got an exception:

现在,当我按下Next键盘中的 时,选择 后firstName,出现异常:

undefined is not an object (evaluating '_this2.refs.lastNameInput.focus')

undefined 不是一个对象(评估 '_this2.refs.lastNameInput.focus')

I'm not sure what I did wrong there.. Any help is appreciated. :)

我不确定我在那里做错了什么.. 任何帮助表示赞赏。:)

回答by Supto

Let's start from the CustomTextInput component.

让我们从 CustomTextInput 组件开始。

export default class CustomTextInput extends Component {

componentDidMount() {
    if (this.props.onRef != null) {
        this.props.onRef(this)
    }
}

onSubmitEditing() {
    this.props.onSubmitEditing();
}

focus() {
    this.textInput.focus()
}


render() {
    return (
        <View>
            <View style={this.state.isFocused ? styles.onFocusedStyle : styles.onBlurStyle}>
                <TextInput
                    ref={input => this.textInput = input}
                    onSubmitEditing={this.onSubmitEditing.bind(this)}
                />
            </View>

            <Text style={styles.errorMessageField}>{this.state.errorStatus && this.props.errorMessage}</Text>
        </View>
    );
}}

Here i have a sample customTextInput. Important things to note here is the componentDidMount(), focus() method and ref property in the TextInput view in render method.

这里我有一个示例 customTextInput。这里需要注意的重要事项是 render 方法中 TextInput 视图中的 componentDidMount()、focus() 方法和 ref 属性。

  1. componentDidMount() method passes the ref of the whole CustomTextInput component to it's parent component. Through that reference we will call the focus method of CustomTextInput component from the parent component.

  2. focus() method here focuses the textInput inside the CustomTextInput component by using the ref of TextInput component inside the CustomTextInput component.

  3. The ref property of TextInput stores the reference of the TextInput. This reference is used by the focus() method.

  1. componentDidMount() 方法将整个 CustomTextInput 组件的 ref 传递给它的父组件。通过该引用,我们将从父组件调用 CustomTextInput 组件的 focus 方法。

  2. 此处的 focus() 方法通过使用 CustomTextInput 组件内的 TextInput 组件的 ref 来聚焦 CustomTextInput 组件内的 textInput。

  3. TextInput 的 ref 属性存储了 TextInput 的引用。该引用由 focus() 方法使用。

Now let's see the parent component

现在让我们看看父组件

export default class ParentComponent extends Component {
constructor(props) {
    super(props);

    this.focusNextField = this.focusNextField.bind(this);
    this.inputs = {};
}


focusNextField(id) {
    this.inputs[id].focus();
}

render() {
    return (
        <ScrollView
            contentContainerStyle={{paddingBottom:100}}
            keyboardDismissMode={'on-drag'}
            scrollToTop={true}>
            <View>
                    <View style={{marginTop: 10}}>
                        <CustomTextInput
                            onRef={(ref) => {
                                this.inputs['projectName'] = ref;
                            }}
                            onSubmitEditing={() => {
                                this.focusNextField('projectDescription');
                            }}
                            />
                    </View>
                    <View style={{marginTop: 10}}>
                        <CustomTextInput
                            onRef={(ref) => {
                                this.inputs['projectDescription'] = ref;
                            }}
                            onSubmitEditing={() => {
                                this.focusNextField('subDivision');
                            }}
                        />
                    </View>
                    <View style={{marginTop: 10}}>
                        <CustomTextInput
                            onRef={(ref) => {
                                this.inputs['subDivision'] = ref;
                            }}
                            onSubmitEditing={() => {
                                this.focusNextField('plan');
                            }}
                           />
                    </View>

                    <View style={{marginTop: 10}}>
                        <CustomTextInput
                            onRef={(ref) => {
                                this.inputs['plan'] = ref;
                            }}
                    </View>
            </View>
        </ScrollView>
    );
}}

Here in the parent component we store the ref of each CustomTextInput with onRef property and when the submit button from keyboard is pressed we call the focus method of the next CustomTextInput and the focus method of CustomTextInput focuses the TextInput inside the child component.

在父组件中,我们使用 onRef 属性存储每个 CustomTextInput 的 ref,当按下键盘上的提交按钮时,我们调用下一个 CustomTextInput 的 focus 方法,CustomTextInput 的 focus 方法将焦点放在子组件内的 TextInput。

回答by Stefan Wüst

Here is a solution that worked for me — basically you make a reference within your custom component, which you can access from your reference in your parent component:

这是一个对我有用的解决方案 - 基本上你在你的自定义组件中创建一个引用,你可以从你的父组件中的引用访问它:

let CustomTextInput = React.createClass({
    propTypes: {
        refName: React.PropTypes.string,
        returnKeyType: React.PropTypes.string,
        onSubmitEditing: React.PropTypes.func
    },

    getDefaultProps: function(){
        return {
            refName: "",
            returnKeyType: "default",
            onSubmitEditing: () => {}
        }
    },

    render: function(){
        return(
            <View>
                <TextInput 
                    ref="input"
                    returnKeyType={this.props.returnKeyType}
                    onSubmitEditing={this.props.onSubmitEditing}
                />
            </View>
        )
    }
});

module.exports = CustomTextInput

And in the parent component:

在父组件中:

let MyParent = React.createClass({
    render: function(){
        return(
            <View>
                <CustomTextInput
                    refName={'firstNameInput'},
                    returnKeyType={'next'}
                    onSubmitEditing={(event) => { 
                        this.lastNameInput.refs.input.focus();
                    }}
                />
                <CustomTextInput
                    refName={ref => this.lastNameInput = ref}
                />
            </View>
        )
    }
});

回答by durga patra

let CustomTextInput = React.createClass({
    componentDidMount() {
        // this is to check if a refName prop is FUNCTION; 
        if (typeof this.props.rex === "function") {
            this.props.refName(this.refs.inp);
        }
    }

    render: function() {
        return(
            <View>
                <TextInput ref={"inp"}/>
            </View>
        )
    }
});

let MyParent = React.createClass({
    render: function() {
        return (
            <View>
                <CustomTextInput
                    refName={ (firstNameInput) => this.firstNameInput = firstNameInput }
                />
            </View>
        )
    }
});

回答by cityvoice

try this:

尝试这个:

let AwesomeProject = React.createClass({
    onSubmitEditing:function(event){
        if (this.myTextInput !== null) {
          this.myTextInput.focus();
        }
    },
    render(){
        return(
            <View>
                <CustomTextInput
                    returnKeyType={'next'}
                    onSubmitEditing={this.onSubmitEditing}
                />
                <CustomTextInput
                    refName={(ref) => this.myTextInput = ref}
                />
            </View>
        )
    }
});