Javascript 点击 react.js 传递 id
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39818569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pass id through on click react.js
提问by Thian Kian Phin
Below is my partial code but my question is very simple, how can I get says data-id="1" to my function when user clicked on the li
?
下面是我的部分代码,但我的问题很简单,当用户单击li
?
render(){
return(
<ul id="todo">
{this.state.items.map((item,i) =>
<li className='list-group-item' key={i} data-id={item.id}>{item.name}
<button onClick={//how to pass item.id to my function?}>X</button>
</li>
)}
</ul>
)
}
回答by syllabix
Since you are already using ES6 - might be a little cleaner to use an arrowfunction here:
由于您已经在使用 ES6 -在这里使用箭头函数可能会更简洁:
render(){
return(
<ul id="todo">
{this.state.items.map((item,i) =>
<li className='list-group-item' key={i} data-id={item.id}>{item.name}
<button onClick={() => this.yourfunc(item.id)}>X</button>
</li>
)}
</ul>
)
}
回答by Pranesh Ravi
You can use bind()
to do this.
您可以使用它bind()
来执行此操作。
render(){
return(
<ul id="todo">
{this.state.items.map((item,i) =>
<li className='list-group-item' key={i} data-id={item.id}>{item.name}
<button onClick={yourfunc.bind(this, item.id)}>X</button>
</li>
)}
</ul>
)
}
Your function will receive item.id
as the first parameter
您的函数将item.id
作为第一个参数接收
回答by Boky
You can do this as follows :
您可以按如下方式执行此操作:
class Test extends React.Component {
constructor(props){
super(props);
this.state = {
items: [
{item: "item", id: 1},
{item1: "item1", id: 2}
]
}
}
handleClick(id, e){
alert(id);
}
render(){
return(
<ul id="todo">
{this.state.items.map((item,i) =>
<li className='list-group-item' key={i} data-id={item.id}>{item.name}
<button onClick={this.handleClick.bind(this, item.id)}>X</button>
</li>
)}
</ul>
)
}
}
React.render(<Test />, document.getElementById('container'));
Here is jsfiddle.
这是jsfiddle。
回答by mayid
In my opinion, you shouldn't declare functions, nor bind methods within rendermethod. Neither of these:
在我看来,你不应该声明函数,也不应该在render方法中绑定方法。这些都不是:
onClick={(e) => this.handleClick(e, item.id)}
onClick={(e) => this.handleClick(e, item.id)}
onClick={this.handleClick.bind(this, item.id)}
onClick={this.handleClick.bind(this, item.id)}
I know it's plenty of tutoriales showing that syntax. But there's also a considerable number of blog posts warning about why that's not a good idea. Basically, you are creating a new function on each render.
我知道有很多教程展示了这种语法。但是也有相当多的博客文章警告为什么这不是一个好主意。基本上,您是在每个渲染上创建一个新函数。
Go check the manual: https://reactjs.org/docs/handling-events.html
去查看手册:https: //reactjs.org/docs/handling-events.html
And I'm aware that in the last two examples it does create functions on render. But react manual also shows this example and says:
而且我知道在最后两个示例中它确实在 render 上创建了函数。但是反应手册也显示了这个例子并说:
class LoggingButton extends React.Component {
handleClick() {
console.log('this is:', this);
}
render() {
// This syntax ensures `this` is bound within handleClick
return (
<button onClick={(e) => this.handleClick(e)}>
Click me
</button>
);
}
}
The problem with this syntax is that a different callback is created each time the LoggingButton renders. In most cases, this is fine. However, if this callback is passed as a prop to lower components, those components might do an extra re-rendering. We generally recommend binding in the constructor or using the class fields syntax, to avoid this sort of performance problem.
此语法的问题在于每次 LoggingButton 呈现时都会创建不同的回调。在大多数情况下,这很好。但是,如果此回调作为道具传递给较低的组件,则这些组件可能会进行额外的重新渲染。我们通常建议在构造函数中绑定或使用类字段语法,以避免此类性能问题。
BETTER SOLUTION
更好的解决方案
So, if you only need to pass one value, then check out the other examples in the manual. Basically you can bindthe method in the constructor (or use an experimental syntax to avoid that step).
因此,如果您只需要传递一个值,请查看手册中的其他示例。基本上,您可以在构造函数中绑定该方法(或使用实验语法来避免该步骤)。
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
And how would you get the id/valuethat you are trying to get? See this example:
您将如何获得您想要获得的id/value?看这个例子:
class App extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick({currentTarget}) {
console.log(currentTarget.value) // e.currentTarget.value would be equivalent
}
render() {
return (
<button value="here!" onClick={this.handleClick}>
Click me
</button>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
body {
padding: 5px;
background-color: white;
}
<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>
<div id="root"></div>
So, if you are using buttons or any form element (accepting a value), you may definitively consider this syntax.
因此,如果您使用按钮或任何表单元素(接受值),您可以明确地考虑这种语法。
回答by cdagli
Below is a running sample;
下面是一个运行示例;
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [{
id: 0,
name: "Buy milk"
}, {
id: 1,
name: "Write unit tests"
}, {
id: 2,
name: "Cook a meal"
}]
}
this.handleClick = this.handleClick.bind(this);
}
handleClick(value) {
console.log(`${value} clicked`);
}
renderTodos() {
return this.state.items.map((item, idx) => {
return ( < li className = 'list-group-item'
key = {
idx
} > {
item.name
} < button onClick = {
() => this.handleClick(item.id)
} > X < /button>
</li >
)
})
}
render() {
return ( < ul id = "todo" > {
this.renderTodos()
} < /ul>
)
}
}
ReactDOM.render(
<App/ > ,
document.getElementById('react_example')
);
<!DOCTYPE html>
<html>
<head>
<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>
<meta charset="utf-8">
</head>
<body>
<div id="react_example"></div>
</body>
</html>
回答by Black
Mayid is correct that it is not good to declare or bind functions in render method if the function is passed into other component as a props.
Mayid 是正确的,如果函数作为道具传递给其他组件,则在渲染方法中声明或绑定函数是不好的。
Unfortunately currentTarget didn't work for me.
不幸的是 currentTarget 对我不起作用。
I have used getAttribute function of event.target. This doesn't cause unnecessary rerenders.
我使用过 event.target 的 getAttribute 函数。这不会导致不必要的重新渲染。
class App extends React.Component {
handleClick = (event) => {
console.log(event.target.getAttribute('index'))
}
render() {
return (
<button index="1" onClick={this.handleClick}>
Click me
</button>
);
}
}