반응 JS onClick 이벤트 핸들러
있습니다
var TestApp = React.createClass({
getComponent: function(){
console.log(this.props);
},
render: function(){
return(
<div>
<ul>
<li onClick={this.getComponent}>Component 1</li>
</ul>
</div>
);
}
});
React.renderComponent(<TestApp />, document.body);
클릭한 목록 요소의 배경을 색칠합니다.리액트에서는 어떻게 하면 좋을까요?
뭐랄까
$('li').on('click', function(){
$(this).css({'background-color': '#ccc'});
});
안 되는 이유:
onItemClick: function (event) {
event.currentTarget.style.backgroundColor = '#ccc';
},
render: function() {
return (
<div>
<ul>
<li onClick={this.onItemClick}>Component 1</li>
</ul>
</div>
);
}
또한 React-live에 대해 더 자세히 알아보려면 선택한 항목을 React 구성 요소가 포함된 상태로 설정한 다음 해당 상태를 참조하여 항목 색상을 결정할 수 있습니다.render:
onItemClick: function (event) {
this.setState({ selectedItem: event.currentTarget.dataset.id });
//where 'id' = whatever suffix you give the data-* li attribute
},
render: function() {
return (
<div>
<ul>
<li onClick={this.onItemClick} data-id="1" className={this.state.selectedItem == 1 ? "on" : "off"}>Component 1</li>
<li onClick={this.onItemClick} data-id="2" className={this.state.selectedItem == 2 ? "on" : "off"}>Component 2</li>
<li onClick={this.onItemClick} data-id="3" className={this.state.selectedItem == 3 ? "on" : "off"}>Component 3</li>
</ul>
</div>
);
},
그걸 넣는 게 좋을 거야<li>를 루프로 만듭니다.또한 이 루프를li.on그리고.li.off스타일 설정background-color.
제가 생각할 수 있는 두 가지 방법은
var TestApp = React.createClass({
getComponent: function(index) {
$(this.getDOMNode()).find('li:nth-child(' + index + ')').css({
'background-color': '#ccc'
});
},
render: function() {
return (
<div>
<ul>
<li onClick={this.getComponent.bind(this, 1)}>Component 1</li>
<li onClick={this.getComponent.bind(this, 2)}>Component 2</li>
<li onClick={this.getComponent.bind(this, 3)}>Component 3</li>
</ul>
</div>
);
}
});
React.renderComponent(<TestApp /> , document.getElementById('soln1'));
이건 내가 제일 좋아하는 거야.
var ListItem = React.createClass({
getInitialState: function() {
return {
isSelected: false
};
},
handleClick: function() {
this.setState({
isSelected: true
})
},
render: function() {
var isSelected = this.state.isSelected;
var style = {
'background-color': ''
};
if (isSelected) {
style = {
'background-color': '#ccc'
};
}
return (
<li onClick={this.handleClick} style={style}>{this.props.content}</li>
);
}
});
var TestApp2 = React.createClass({
getComponent: function(index) {
$(this.getDOMNode()).find('li:nth-child(' + index + ')').css({
'background-color': '#ccc'
});
},
render: function() {
return (
<div>
<ul>
<ListItem content="Component 1" />
<ListItem content="Component 2" />
<ListItem content="Component 3" />
</ul>
</div>
);
}
});
React.renderComponent(<TestApp2 /> , document.getElementById('soln2'));
DEMO가 있습니다.
이게 도움이 됐으면 좋겠어요.
다음은 질문 제목에 응답하는 react onClick 이벤트 핸들러를 정의하는 방법입니다.es6 구문 사용
import React, { Component } from 'react';
export default class Test extends Component {
handleClick(e) {
e.preventDefault()
console.log(e.target)
}
render() {
return (
<a href='#' onClick={e => this.handleClick(e)}>click me</a>
)
}
}
ECMA2015를 사용합니다.화살표 기능은 "이것"을 훨씬 더 직관적으로 만듭니다.
import React from 'react';
class TestApp extends React.Component {
getComponent(e, index) {
$(e.target).css({
'background-color': '#ccc'
});
}
render() {
return (
<div>
<ul>
<li onClick={(e) => this.getComponent(e, 1)}>Component 1</li>
<li onClick={(e) => this.getComponent(e, 2)}>Component 2</li>
<li onClick={(e) => this.getComponent(e, 3)}>Component 3</li>
</ul>
</div>
);
}
});
React.renderComponent(<TestApp /> , document.getElementById('soln1'));`
ES6 를 사용하고 있는 경우는, 다음의 간단한 코드 예를 나타냅니다.
import React from 'wherever_react_is';
class TestApp extends React.Component {
getComponent(event) {
console.log('li item clicked!');
event.currentTarget.style.backgroundColor = '#ccc';
}
render() {
return(
<div>
<ul>
<li onClick={this.getComponent.bind(this)}>Component 1</li>
</ul>
</div>
);
}
}
export default TestApp;
ES6 클래스 본문에서는 함수는 'function' 키워드를 필요로 하지 않게 되어 콤마로 구분하지 않아도 됩니다.=> 구문을 사용할 수도 있습니다.
다음은 동적으로 작성된 요소의 예입니다.
import React from 'wherever_react_is';
class TestApp extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [
{name: 'Name 1', id: 123},
{name: 'Name 2', id: 456}
]
}
}
getComponent(event) {
console.log('li item clicked!');
event.currentTarget.style.backgroundColor = '#ccc';
}
render() {
<div>
<ul>
{this.state.data.map(d => {
return(
<li key={d.id} onClick={this.getComponent.bind(this)}>{d.name}</li>
)}
)}
</ul>
</div>
);
}
}
export default TestApp;
동적으로 생성된 각 요소에는 고유한 참조 '키'가 있어야 합니다.
또한 이벤트가 아닌 실제 데이터 개체를 onClick 함수에 전달하려면 바인드에 전달해야 합니다.예를 들어 다음과 같습니다.
새로운 onClick 기능:
getComponent(object) {
console.log(object.name);
}
데이터 개체 전달:
{this.state.data.map(d => {
return(
<li key={d.id} onClick={this.getComponent.bind(this, d)}>{d.name}</li>
)}
)}
React 요소를 사용하여 이벤트를 처리하는 것은 DOM 요소에서 이벤트를 처리하는 것과 매우 유사합니다.구문적인 차이가 몇 가지 있습니다.
- 리액트 이벤트의 이름은 소문자가 아닌 camelCase를 사용하여 지정됩니다.
- JSX에서는 문자열이 아닌 이벤트핸들러로서 함수를 전달합니다.
리액트 문서에서 설명한 바와 같이 이벤트 처리와 관련하여 일반 HTML과 상당히 유사하지만, 카멜케이스 사용 리액트에서는 이벤트 이름은 실제로 HTML이 아니기 때문에 JavaScript입니다.또한 함수 호출을 HTML용 문자열 형식으로 전달할 때 함수를 전달합니다.다르지만 개념은 상당히 비슷합니다.
다음 예시를 보고 이벤트가 함수로 전달되는 방법에 주의하십시오.
function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('The link was clicked.');
}
return (
<a href="#" onClick={handleClick}>
Click me
</a>
);
}
import React from 'react';
class MyComponent extends React.Component {
getComponent(event) {
event.target.style.backgroundColor = '#ccc';
// or you can write
//arguments[0].target.style.backgroundColor = '#ccc';
}
render() {
return(
<div>
<ul>
<li onClick={this.getComponent.bind(this)}>Component 1</li>
</ul>
</div>
);
}
}
export { MyComponent }; // use this to be possible in future imports with {} like: import {MyComponent} from './MyComponent'
export default MyComponent;
class FrontendSkillList extends React.Component {
constructor() {
super();
this.state = { selectedSkill: {} };
}
render() {
return (
<ul>
{this.props.skills.map((skill, i) => (
<li
className={
this.state.selectedSkill.id === skill.id ? "selected" : ""
}
onClick={this.selectSkill.bind(this, skill)}
style={{ cursor: "pointer" }}
key={skill.id}
>
{skill.name}
</li>
))}
</ul>
);
}
selectSkill(selected) {
if (selected.id !== this.state.selectedSkill.id) {
this.setState({ selectedSkill: selected });
} else {
this.setState({ selectedSkill: {} });
}
}
}
const data = [
{ id: "1", name: "HTML5" },
{ id: "2", name: "CSS3" },
{ id: "3", name: "ES6 & ES7" }
];
const element = (
<div>
<h1>Frontend Skill List</h1>
<FrontendSkillList skills={data} />
</div>
);
ReactDOM.render(element, document.getElementById("root"));
.selected {
background-color: rgba(217, 83, 79, 0.8);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
@user544079 이 데모가 도움이 되기를 바랍니다:) 클래스 이름을 바꿈으로써 배경색을 변경할 것을 권장합니다.
import React from 'react';
class MyComponent extends React.Component {
getComponent(event) {
event.target.style.backgroundColor = '#ccc';
// or you can write
//arguments[0].target.style.backgroundColor = '#ccc';
}
render() {
return(
<div>
<ul>
<li onClick={this.getComponent.bind(this)}>Component 1</li>
</ul>
</div>
);
}
}
export { MyComponent }; // use this to be possible in future imports with {} like: import {MyComponent} from './MyComponent'
export default MyComponent;
React.createClone 메서드를 사용할 수 있습니다.요소의 클론을 작성하는 것보다 요소를 작성합니다.클론을 만드는 동안 소품을 주입할 수 있습니다.다음과 같은 onClick : 메서드 프로펠을 삽입합니다.
{ onClick : () => this.changeColor(originalElement, index) }
changeColor 메서드는 중복된 상태를 설정하므로 프로세스에서 색상을 설정할 수 있습니다.
render()
{
return(
<ul>
{this.state.items.map((val, ind) => {
let item = <li key={ind}>{val}</li>;
let props = {
onClick: () => this.Click(item, ind),
key : ind,
ind
}
let clone = React.cloneElement(item, props, [val]);
return clone;
})}
</ul>
)
}
이것은 JSX를 사용하지 않고 모든 것을 인라인화하는 비표준 반응 패턴입니다.그리고 Cofeescript입니다.
이를 위한 'React-way'는 구성 요소 자체의 상태에 따라 달라집니다.
)c = console.log.bind console)
mock_items: [
{
name: 'item_a'
uid: shortid()
}
{
name: 'item_b'
uid: shortid()
}
{
name: 'item_c'
uid: shortid()
}
]
getInitialState: ->
lighted_item: null
render: ->
div null,
ul null,
for item, idx in @mock_items
uid = item.uid
li
key: uid
onClick: do (idx, uid) =>
(e) =>
# justf to illustrate these are bound in closure by the do lambda,
c idx
c uid
@setState
lighted_item: uid
style:
cursor: 'pointer'
background: do (uid) =>
c @state.lighted_item
c 'and uid', uid
if @state.lighted_item is uid then 'magenta' else 'chartreuse'
# background: 'chartreuse'
item.name
이 예제는 동작합니다.로컬로 테스트했습니다.이 샘플 코드는 제 github에서 확인하실 수 있습니다.원래 환경은 내 화이트보드 R&D 목적으로만 로컬이었지만, 이를 위해 Github에 게시했습니다.어느 시점에 쓰여질 수도 있지만 2016년 9월 8일부터 이 내용을 확인하실 수 있습니다.
보다 일반적으로 이 React용 CS/no-JSX 패턴의 구조를 확인하려면 여기서 몇 가지 최신 작업을 확인하십시오.NodeJs, Primus, Redis 및 React를 포함하는 스택에 대한 POC를 완전히 구현할 수 있습니다.
언급URL : https://stackoverflow.com/questions/28511207/react-js-onclick-event-handler
'codememo' 카테고리의 다른 글
| ng-click을 사용하여 두 가지 함수를 호출합니다. (0) | 2023.02.22 |
|---|---|
| --eslint를 사용해도 오류는 수정되지 않습니다. (0) | 2023.02.22 |
| Oracle ORDER BY 및 ROWNUM을 올바르게 사용하는 방법 (0) | 2023.02.18 |
| 각도 UI 라우터가 비동기 데이터를 해상도로 가져옵니다. (0) | 2023.02.16 |
| Android에서 json 생성 (0) | 2023.02.16 |