[英]onClick and className not working in reactjs
Onclick 在此組件中不起作用。 這是我第一次遇到這個錯誤,我嘗試過代碼,我已經將所有函數綁定到this
,但onClick
方法根本不起作用。 我添加到Col
內的div
任何 className 也沒有被應用。
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Row, Col } from 'antd';
import { safariTypes } from '../../data/safariTypes';
import uuid from 'uuid/v1';
import '../../App.css';
const ThePeople = './Media/thePeople.jpeg';
const BoraBora = './Media/bora.jpg';
const Aerial = './Media/balloon.jpg';
const Family = './Media/family_small.jpg';
const Honeymoons = './Media/honeymoon_small.jpg';
const Wildlife = './Media/wildlife.jpg';
class Highlights extends Component {
constructor(props) {
super(props);
this.state = {
}
this.returnSafariItemsHighlights = this.returnSafariItemsHighlights.bind(this)
this.show = this.show.bind(this)
}
show = () => {
console.log("hey");
}
returnSafariItemsHighlights(){
var Feature = null
var arr = []
if(safariTypes){
safariTypes.slice(0,6).map((item, key) => {
if(item === 'Aerial e.g Hot air ballons'){
Feature = Aerial
} else if(item === 'Wildlife') {
Feature = Wildlife
} else if(item === 'Family and Holiday') {
Feature = Family
} else if(item === 'Beach Holidays') {
Feature = BoraBora
} else if(item === 'Culture and History') {
Feature = ThePeople
} else if(item === 'Honeymoons'){
Feature = Honeymoons
}
arr.push(
<Col xs={24} sm={12} md={12} lg={8} xl={8} key={uuid()} onClick={this.show} >
<div
className="bounceAnimation"
style={{ backgroundImage: 'url(' + Feature + ')',
backgroundSize: 'cover',
backgroundPosition: 'center center',
backgroundRepeat: 'no-repeat',
height: '40vh',
paddingTop: '28vh',
paddingLeft: '20px',
paddingRight: '20px'
}}>
<div style={{backgroundColor: "rgb(255, 255, 255, 0.4)", textAlign: "center", fontSize: "25px",padding: "5px", fontFamily: "Lobster", color: "green"}}>
#{item}
</div>
</div>
</Col>
)
})
}
return arr
}
render() {
return (
<div>{this.returnSafariItemsHighlights()}</div>
);
}
}
似乎 Col 不接受 onClick onClick={this.show}
,為什么不將onClick={this.show}
移動到 Col 內的 div 如下
<Col
xs={24} sm={12} md={12} lg={8} xl={8} key={uuid()} >
<div
onClick={this.show}
className="bounceAnimation"
style={{ backgroundImage: 'url(' + Feature + ')', ...}}
>
...
</div>
</Col>
我想我發現了一個性能問題,每次組件渲染時它都會調用returnSafariItemsHighlights
,在那里你用每次調用函數時生成的 key prop 填充一個組件數組,當 react 協調時,它會在這種情況下找到不同的鍵子組件不會被重用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.