나는 매우 간단해야 할 노력하고있어하지만 내가 사용하는 특정 구성 요소를 참조하여 얻을 수 아니에요 보이는 이
그래서 여기에 App.js가 있습니다.
import React, { Component } from 'react';
import CoolBox from './coolBox.js';
import './App.css';
class App extends Component {
changeColor(){
$(this).css('background','blue');
}
render() {
return (
<div className="App">
<CoolBox changeColor={function(){ this.changeColor() }.bind(this)} />
<CoolBox changeColor={function(){ this.changeColor() }.bind(this)} />
<CoolBox changeColor={function(){ this.changeColor() }.bind(this)} />
</div>
);
}
}
export default App;
그리고 여기에 빨간색 배경의 간단한 상자 인 CoolBox.js가 있습니다.
import React, { Component } from 'react';
import $ from 'jquery';
class CoolBox extends Component {
render() {
return (
<div onClick={this.props.changeColor} className="box"></div>
);
}
}
export default CoolBox;
이제 제가 달성하려는 것은 3 개의 상자 중 하나를 클릭하면 클릭 한 특정 상자에서만 배경색이 변경됩니다.
$ (this) 를 참조 할 수없는 경우 jquery 메서드를 사용할 수없는 것 같습니다 . 그렇다면 React 내에서이 간단한 기능을 어떻게 달성 할 수 있습니까?
You don't need jQuery for this. There are couple of way to reference components in the DOM and there are couple of patterns of such components(controlled and uncontrolled) you should read about it.
As for you solution, this is a simple solution just to get you start with.
On event handlers you can access the event
as an argument. changeColor(e)
as e
is the object that holds the event information as well as the target
(the div
you clicked in your case).
So basically what you can do in App.js
is this:
class App extends React.Component {
constructor(props){
super(props);
this.changeColor = this.changeColor.bind(this);
}
changeColor(e){
e.target.style.background = "blue";
}
render() {
return (
<div className="App">
<CoolBox changeColor={this.changeColor} />
<CoolBox changeColor={this.changeColor} />
<CoolBox changeColor={this.changeColor} />
</div>
);
}
}
Please note
As you can see i bind the handler in the constructor instead of in the render
method. that way you only bind it once and not on each render call witch will create a new instance on each render. that is better for performance.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다