图像库是一组带有相应移除按钮的图像。这是一个包含两个图像的库的HTML代码:
<div>
<div class="image">
<img src="URL1">
<button class="remove">X</button>
</div>
<div class="image">
<img src="URL2">
<button class="remove">X</button>
</div>
</div>
实现ImageGallery组件,该组件接受链接道具并渲染上面描述的库,以便链接道具中的第一个项目是库中第一个图像的src属性。它还应该实现以下逻辑:当单击按钮时,应该从库中删除与按钮位于同一div中的图像。
例如,从上面的图库中删除第一个图像后,它的HTML代码应该如下所示:
<div>
<div class="image">
<img src="URL2">
<button class="remove">X</button>
</div>
</div>
这是我实现的解决方案,但它没有通过测试用例
class ImageGallery extends React.Component {
constructor() {
super();
}
remove = e => {
Array.prototype.forEach.call(
document.getElementsByClassName("remove"),
function(elem) {
elem.onclick = () => elem.parentNode.remove();
}
);
};
render() {
return (
<div>
{this.props.links.map((item, index) => {
return (
<div key={item} className="image">
<img key={index} src={item} />{" "}
<button className="remove" onClick={this.remove}>
X
</button>
</div>
);
})}
</div>
);
}
}
document.body.innerHTML = "<div id='root'> </div>";
const rootElement = document.getElementById("root");
const links = ["URL1", "URL2"];
ReactDOM.render(<ImageGallery links={links} />, rootElement);
document.querySelectorAll(".remove")[0].click();
console.log(rootElement.innerHTML);
这是一个沙盒演示-https://codesandbox.io/s/testdome-react-1-focus-7qbp1?file=/src/index.js
有关测试用例的详细信息,请参阅问题5https://www.testdome.com/d/react-js-interview-questions/304
您不需要外部事件侦听器,也不需要删除dom节点,如果您在做出反应时不需要这样做的话。以下是如何做到这一点。
更新的沙盒:https://codesandbox.io/s/testdome-react-1-focus-4627z?file=/src/index.js
class ImageGallery extends React.Component {
constructor(props) {
super(props);
this.state = { links: props.links };
}
remove = url => {
console.log(url)
this.setState(state => ({
links: state.links.filter(l => l !== url)
}));
};
render() {
const { links } = this.state;
return (
<div>
{links.map((item, index) => {
return (
<div key={item} className="image">
<img key={index} src={item} alt="" />{" "}
<button className="remove" onClick={() => this.remove(item)}>
X
</button>
</div>
);
})}
</div>
);
}
}
这是的正确答案
class ImageGallery extends React.Component {
constructor(props) {
super(props);
this.state = { links: props.links };
}
remove = index => {
var list = this.state.links
list.splice(index,1);
this.setState({links:list})
};
render() {
return (
<div>
{this.state.links.map((item, index) => {
return (
<div key={item} className="image">
<img key={index} src={item} alt="" />
<button className="remove" onClick={() => this.remove(index)}>
X
</button>
</div>
);
})}
</div>
);
}
}
document.body.innerHTML = "<div id='root'> </div>";
const rootElement = document.getElementById("root");
const links = ["www.goo.gl/kjzfbE", "www.goo.gl/d2JncW"];
ReactDOM.render(<ImageGallery links={ links } />,
rootElement);
document.querySelectorAll('.remove')[0].click();
console.log(rootElement.innerHTML);