简体   繁体   English

在React中改变对子组件的关注的更清洁的方法

[英]Cleaner way to change focus on child components in React

I'm trying to figure out a cleaner way to use arrow keys to move focus up and down in a list of inputs using React. 我正试图找出一种更简洁的方法来使用箭头键在使用React的输入列表中上下移动焦点。 The list is the parent component, the input the children. 列表是父组件,输入子组件。 In order to figure out what input should be focused next, I'm giving each child a ref as well as a numeric id that I use to track ordering. 为了弄清楚接下来应该关注什么输入,我给每个孩子一个ref以及我用来跟踪排序的数字id When an arrow key is detected, the callback then finds the child with the correct ref and goes into that child's refs to grab the input and give it focus. 当检测到箭头键时,回调然后找到具有正确ref的子进入并且进入该子refsrefs以获取输入并给予焦点。

I'm new at React, this feels quite dirty, thus I'm wondering if there's a cleaner solution. 我是React的新手,感觉很脏,所以我想知道是否有更清洁的解决方案。

Code and working jsfiddle: 代码和工作jsfiddle:

var Child = React.createClass({
    handleUp: function(e) {
        switch(e.key) {
            case "ArrowDown":
                this.props.handleFocus(this.props.id+1);
            break;
            case "ArrowUp":
                this.props.handleFocus(this.props.id-1);            
            break;
        }
    },
    render: function() {
        return <div><input defaultValue={this.props.name} onKeyUp={this.handleUp} ref="input" /></div>;
    }
});

var Parent = React.createClass({
    handleFocus: function(id) {
        var child = this.refs['child' + id];
        if (!child) return;
        var input = child.refs.input;
        input.getDOMNode().focus();
    },
    render: function() {
        var inputs = [];
        for (var i=0; i<10; i++) {
            inputs.push(<Child key={i} id={i} name={"value" + i} handleFocus={this.handleFocus} ref={'child' + i} />);
        }
        return <div>
            {inputs}
        </div>;
    }
});

http://jsfiddle.net/69z2wepo/509/ http://jsfiddle.net/69z2wepo/509/

There are a few ways to do this, but none are really 'better' than this. 有几种方法可以做到这一点,但没有一种方法比这更好。

The alternatives would use a mixin, but that brings in the mental cost of black box abstraction for little gain. 替代方案将使用mixin,但这会带来黑盒抽象的心理成本,而收益微乎其微。 I'd just keep it as is. 我只是保持原样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM