是否有可能有一个动态参考在反应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()}
</>
);
}
}发布于 2019-09-04 07:10:26
通过更新以下两种方法,您将得到解决方案。
在id方法中传递hide方法。
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";
}希望这能帮上忙!
发布于 2019-09-04 07:21:27
您可以使用下面的片段。我已经更新了你的课程。只需将"id“传递给隐藏方法即可。
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()}
</>
);
}
}https://stackoverflow.com/questions/57783107
复制相似问题