클릭: 작동하지 않음 반응 js
사용자가 div를 클릭하면 함수를 호출하려고 합니다(onClick in react 사용).지금은 어떤 논쟁도 할 필요가 없습니다. 함수만 부르면 됩니다.제가 모르는 것에 대해 미리 사과드립니다.감사해요.
var Test = React.createClass({
btnTapped: function(){
console.log('tapped!');
},
render: function() {
var stationComponents = this.props.stations.map(function(station, index) {
return <div onClick={btnTapped()}><img src="img/test.png" />{station}</div>;
});
return <div>{stationComponents}</div>;
}
});
var cards = ["amazon", "aeo", "aerie", "barnes", "bloomingdales", "bbw","bestbuy", "regal", "cvs", "ebay", "gyft", "itunes", "jcp", "panera", "staples", "walmart", "target", "sephora", "walgreens", "starbucks"];
ReactDOM.render(<Test stations={cards} />, document.getElementById('test-div'));
빌드 시스템에서 babel을 지원하는 경우 반응 코드에서 ES6 화살표 기능을 사용합니다.
컴포넌트 작성에 ES6 클래스를 사용하는 경우 컨스트럭터레벨에서 메서드바인딩을 사용하여 모든 렌더 콜에서 바인딩을 회피하고 맵함수 내의 div 태그에 키를 지정합니다.
class Test extends React.Component {
constructor(props) {
super(props);
this.btnTapped = this
.btnTapped
.bind(this);
}
btnTapped() {
console.log('tapped');
}
render() {
return (
<div>
{this
.props
.stations
.map((station, index) => {
return <div key={index} onClick={this.btnTapped}>{station}</div>
})
}
</div>
)
}
}
var cards = ["amazon", "aeo", "aerie", "barnes", "bloomingdales", "bbw", "bestbuy", "regal", "cvs", "ebay", "gyft", "itunes", "jcp", "panera", "staples", "walmart", "target", "sephora", "walgreens", "starbucks"];
ReactDOM.render(
<Test stations={cards}/>, document.getElementById('test-div'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<body>
<div id="test-div"></div>
</body>
함수는 다음과 같이 설정해야 합니다.onClick
속성, 호출이 아닙니다.다음 항목이어야 합니다.onClick={this.btnTapped}
대신onClick={btnTapped()}
.
또, 다음과 같이 할 수 있습니다.
<div
onClick={function(e) {
this.btnTapped(); //can pass arguments this.btnTapped(foo, bar);
}}
>
이것은 보통 자신의 함수에 인수를 전달해야 할 때 사용합니다.
또한 외부 기능에서 컴포넌트의 컨텍스트를 가져오려면bind(this)
방법.예를 들어 다음과 같습니다.onClick={btnTapped.bind(this)}
또한 배열을 매핑하기 위해 스코프 함수를 사용하므로 다음 영역에 새로운 컨텍스트가 생성됩니다.this.props.stations.map(function(station, index){}
.그리고.this
오버라이드 됩니다.대신 화살표 기능을 사용하십시오.
var stationComponents = this.props.stations.map((station, index) => {
return <div onClick={this.btnTapped}><img src="img/test.png" />{station}</div>;
});
주의: reactjs 전문가가 아닙니다. : )
저는 지금 리액션즈 탐사를 하고 있는데version 16.3.1
화살표 기능은 나에게 효과가 있었다.
<button
onClick={() => { console.log("button clicked");}}>
button
</button>
이것은 다소 이해하기 어려운 설명이지만, onClick() 함수의 철자를 체크해 주세요.onclick()처럼 철자를 잘못 입력해서 알아내는 데 시간이 많이 걸렸습니다.
2021년에 같은 문제에 직면했지만, 위의 답변은 도움이 되지 않았기 때문에, 이것은 오래된 투고입니다.
나는 덧붙였다.bundle.js
내 안에서index.html
파일. 그리고html-webpack-plugin
저를 위해서도 추가해 주셨어요.싣고 있는bundle.js
두 번이 문제의 원인인 것 같습니다.index.html에서 해당 참조를 삭제한 후 정상적으로 동작했습니다.
놓치셨네요this
키워드를 지정합니다.또한 호출하지 않고 함수를 제공해야 합니다.
<div onClick={this.btnTapped}>
갱신:
네가 다시 정의한다는 걸 놓쳤어this
맵 콜백 함수에서 사용됩니다.
화살표 기능 사용
this.props.stations.map((station, index) => {
return <div onClick={this.btnTapped}><img src="img/test.png" />{station}</div>;
});
또는 콘텍스트를 기능에 바인드합니다.
this.props.stations.map(function (station, index) {
return <div onClick={this.btnTapped}><img src="img/test.png" />{station}</div>;
}.bind(this));
렌더 메서드에서 함수를 사용하려면 먼저 생성자에서 이러한 메서드를 바인딩해야 합니다.또 하나, 호출할 필요가 있는 메서드에 인수를 전달하지 않을 때는 이 명령을 사용합니다.onClick = {this.btnTapped}
대신onClick = {this.btnTapped()}
.감사해요.
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
export default class Test extends Component {
constructor (props) {
super(props);
//set cards value in state then you don't need to use props...
this.state = {
cards: ["amazon", "aeo", "aerie", "barnes", "bloomingdales",
"bbw","bestbuy", "regal", "cvs", "ebay", "gyft", "itunes",
"jcp", "panera", "staples", "walmart", "target", "sephora",
"walgreens", "starbucks"]
}
this.btnTapped = this.btnTapped.bind(this);
// bind all the methods which you're using the "this.state" inside it....
}
btnTapped (card) {
console.log("Coming here:::" + card)
}
render() {
var cards = this.state.cards
return (
<div>
{/* if you don't want to pass an arguments use this... */}
{
cards.map((card, i) =>
<button key = {i} onClick = {this.btnTapped}>{card}</button>
)
}
{/* if you want to pass arguments use this */}
{
cards.map((card, i) =>
<button key = {i} onClick = {(e) => this.btnTapped(card)}>{card}</button>
)
}
</div>
);
}
}
ReactDOM.render(<Test />, document.getElementById('test-div'));
이 스레드의 답변으로 문제가 해결되지 않은 사람을 위해 2센트만 지불합니다.비슷한 문제에 직면했는데 디버깅을 한 결과 버튼의 z-index가 -9999로 레이어 뒤에 있어 클릭이 닿지 않았습니다.z-index를 양수 값 1로 변경했더니 클릭이 캡처되었습니다.
이 문제에 직면한 사용자의 경우 CSS의 문제가 원인일 수도 있습니다.
저는 "pointer-events"라는 이름의 CSS 속성을 삭제함으로써 동작했습니다.제 CSS에서는 none으로 설정되어 있습니다.
pointer-events: none;
방금 CSS에서 삭제했는데 클릭 이벤트가 React에서 작동합니다!
웹 팩을 사용하는 경우 webpack.config.js(일반적으로 bundle.js)에서 설정한 출력 파일이 index.html 파일에 추가되지 않았는지 확인합니다.
이것으로 나는 그 문제를 해결했다.
다음과 같은 고전적인 JS 방식을 피하다
test(){ console.log('test') }
대신 다음과 같은 콜백 효과를 사용합니다.
test = () => { console.log('test') }
도움이 되는지 말해라
내 경우 단추가 들어 있는 div가 바깥쪽 div로 감겨져 있었다.그 때문에 이벤트가 트리거되지 않았습니다.버튼 옆에 입력란도 있었는데, 그 외부 div 때문에 입력란을 클릭할 수 없었습니다.
무엇이 문제의 원인인지 이해하기 위해, 나는 주변의 디바에 빨간 테두리를 더하고 나서 나의 주요 디바를 감싸고 있는 바깥쪽 디바에 대해 알게 되었다.
그래서 그런 문제에 대한 저의 제안은 다음과 같은 주변 요소에 경계를 추가하는 것입니다.
border: '1px solid red'
그런 다음 무엇이 이벤트를 제한하는지 알아냅니다.
언급URL : https://stackoverflow.com/questions/38401902/onclick-not-working-react-js
'programing' 카테고리의 다른 글
create-react-app은 언제 코드를 난독화 또는 최소화합니까? (0) | 2023.03.04 |
---|---|
Angular를 사용한 파일 업로드JS (0) | 2023.03.04 |
WordPress 쇼트 코드 내에서 자동 서식 사용 안 함 (0) | 2023.03.04 |
의존성 주입 용기의 이점은 무엇입니까? (0) | 2023.03.04 |
스프링 부트 핫 스왑 (0) | 2023.03.04 |