- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是 react 新手,我只是想知道从另一个组件内创建的组件接收值(value)的最佳解决方案是什么,这将是反模式。我有这两个组件 - mainComponent 有带有图像链接的变量,我刚刚创建了图像并保存了图片表中的索引值。在 Canvas 中我正在渲染这个图像。我只想保存单击图像的索引,创建从 img 对象返回值的函数将是一个很好的解决方案吗?或者它是反模式,我应该尝试另一种方法来实现这个?
class MainComponent extends React.Component {
constructor(){
super();
this.imageCol = ['link','link']
this.state={
indexOfImage : 0,
};
}
render() {
return (
<div>
<div>
{this.imageCol.map((e,index) => {
return <Image value ={index} source={this.imageCol[index]} key={index} style={this._returnState(index)} />
})}
</div>
<div>
<ReactCanvas image={this.imageCol[this.state.indexOfImage]}/>
</div>
</div>
);
}
}
class Image extends React.Component {
constructor(props){
super(props);
}
render() {
return (
<img value ={this.props.value} onClick={ ()=>{console.log('click'+this.props.value)} } className={this.props.style} src={this.props.source}/>
);
}
}
export default Image;
最佳答案
您只需将一个函数传递给 Image
组件的 onclick
即可。那不会是反模式。事实上,应该这样做。
constructor(){
...
}
clickHandler(index){
console.log("index of the clicked image = "+index)
}
render() {
return (
<div>
<div>
{this.imageCol.map((e,index) => {
// pass a function as a prop like this
return <Image onClick={this.clickHandler.bind(this,index)} value ={index} source={this.imageCol[index]} key={index} style={this._returnState(index)} />
})}
</div>
<div>
<ReactCanvas image={this.imageCol[this.state.indexOfImage]}/>
</div>
</div>
);
}
然后在图像组件中只需调用作为 prop 传递给此组件的 onclick
函数
render() {
return (
<img value ={this.props.value} onClick={this.props.onClick} className={this.props.style} src={this.props.source}/>
);
}
关于javascript - Antipattern React - 从其他组件获取值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47163523/
我一直看到一些问题引用了数据库表中名为 DateLastUpdated 的列。我不明白。 我见过的唯一伴随字段是 LastUpdateUserId 等。从来没有关于更新发生原因的指示;甚至更新是什么。
我发现很难理解“延迟反模式”。我想我原则上理解它,但我还没有看到一个 super 简单的例子来说明什么是服务,具有不同的 promise 和反模式,所以我想我会尝试制作自己的服务,但看到我不是这样 s
我被下面两段代码搞糊涂了: 代码1: describe('suit', function(){ before(() => { this.suitData = 'suitdata
我是 react 新手,我只是想知道从另一个组件内创建的组件接收值(value)的最佳解决方案是什么,这将是反模式。我有这两个组件 - mainComponent 有带有图像链接的变量,我刚刚创建了图
我有一个相对复杂的泛型类型(比如 Map> ),我在类内部使用它。 (没有外部可见性;它只是一个实现细节。)我想将其隐藏在 typedef 中,但 Java 没有这样的设施。 昨天我重新发现了以下成语
在 2 个 ViewModel 之间进行通信的常用方法是:MVVM- View Model-View Model Communications 中介者模式或信使类。但是一个窗口中有 6 个 ViewM
TL;DR 在底部。 我继承了一个设计相当糟糕的表,其中保存了针对第三方网络服务的请求日志。该表包含一个时间戳、两个名为metadata_1 和metadata_2 的字段(允许您识别用户)以及一个名
我一直在阅读实现轮询功能的方法,并在 https://davidwalsh.name/javascript-polling 上找到了一篇很棒的文章.现在使用 setTimeout 而不是 setInt
参见此处:https://reactjs.org/blog/2015/12/16/ismounted-antipattern.html还有这里:How to cancel a fetch on com
我是一名优秀的程序员,十分优秀!