【问题标题】:Is it possible to have a dynamic ref in react js?react js中是否可以有动态引用?
【发布时间】:2019-09-04 07:03:04
【问题描述】:

是否可以在 react js 中有动态引用。

我想在 span 的 ref 中分配一个动态值。

我不知道如何调用动态引用。

class Test extends React.Component {
    constructor() {
        super();
    }

    hide = () =>{
        const span = this.refs.ref-1; // I dont have any idea how to call the dynamic ref here.
        span.className = "hidden";
    }

    table = () =>{   
        //postD is something axios request;

        const tableDetail = Object.keys(postD).map((i) => (
                <div key={i}>
                    <h2>{ postD[i].title }</h2>
                    <p>{ postD[i].content }</p> 

                    <span ref={"ref-"+postD[i].id} id="test">The Quick Brown Fox.</span> --> the ref is like ref="ref-1" and ref="ref-2" and ref="ref-3" so on.. it is dynamic 
                    <button onClick={() => this.hide()} >Like</button>
                </div>
    }

    render() {
        return (
            <>  
                <h2>Table</h2>
                {this.table()}
            </>
        );
    }
}

【问题讨论】:

  • 为什么每个跨度都需要 ref?也许这个要求可以通过其他方法来实现。

标签: reactjs ref


【解决方案1】:

通过更新以下两种方法,您将获得解决方案。

hide 方法中传递id

  table = () => {
    const tableDetail = Object.keys(postD).map((i) => (
      <div key={i}>
        <h2>{postD[i].title}</h2>
        <p>{postD[i].content}</p>
        <span ref={`ref-${postD[i].id}`} id={`test-${postD[i].id}`}>The Quick Brown Fox.</span>
        <button onClick={() => this.hide(postD[i].id)} >Like</button>
      </div>
    ));
  }

使用相同的id 获取参考。

hide = (id) => {
  const span = ReactDOM.findDOMNode(this.refs[`ref-${id}`]);
  span.className = "hidden";
}

希望这会有所帮助!

【讨论】:

  • @larp 如果它适合您,那么请接受这个答案,这样它对其他开发人员也有帮助。
  • 类名中没有添加“隐藏”。
  • 我已经更新了我的答案。您必须使用ReactDOM.findDOMNode 来添加类名。
  • 你在项目中使用了哪个版本的 react?
  • 哦,是的。你说的对。我已经更新了我的答案。您能否接受它,以便对其他开发人员也有帮助。
【解决方案2】:

你可以使用下面的sn-p。我已经更新了你的课程。只需将“id”传递给 hide 方法。

    class Test extends React.Component {
        constructor() {
            super();
        }

        hide = (id) => {
            const span = this.refs[`ref-${id}`]; 
            span.ClassName = "hidden";
        }

        table = () => {       
            const tableDetail = Object.keys(postD).map((i) => (
                    <div key={postD[i].id}>
                        <h2>{postD[i].title }</h2>
                        <p>{postD[i].content }</p> 
                        <span ref={`ref-${postD[i].id}`} id={`${postD[i].id}`}>The Quick Brown Fox.</span>
                        <button onClick={() => this.hide(postD[i].id)} >Like</button>
                    </div>
        }

        render() {
            return (
                <>  
                    <h2>Table</h2>
                    {this.table()}
                </>
            );
        }
    }

【讨论】:

    猜你喜欢
    • 2016-11-16
    • 1970-01-01
    • 2017-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多