App下載

react點(diǎn)擊事件怎么實(shí)現(xiàn)?代碼分享!

猿友 2021-06-05 16:06:03 瀏覽數(shù) (2665)
反饋

當(dāng)我們在學(xué)過基礎(chǔ)的前端知識之后,接下來的就是要進(jìn)行深一步的學(xué)習(xí)了。那么今天小編就來說說關(guān)于“react點(diǎn)擊事件怎么實(shí)現(xiàn)?代碼分享!”吧!


一、傳數(shù)組下標(biāo)給點(diǎn)擊事件文件

首先我們新建一個(gè)新的項(xiàng)目之后通過定義一個(gè)數(shù)組,并且在組件中通過對循環(huán)進(jìn)行渲染,在將每個(gè)渲染出來的 ?li ?組件綁定相對于的按鍵和點(diǎn)擊事件,最后在通過把該組件中的關(guān)鍵參數(shù)傳遞給?handleClick?函數(shù),代碼如下:

const A = 65 

class Alphabet extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.state = {
justClicked: null,
letters: Array.from({length: 26}, (_, i) => String.fromCharCode(A + i))
};
}
handleClick(letter) {
this.setState({ justClicked: letter });
}
render() {
return (
<div>
	Just clicked: {this.state.justClicked}
	<ul>
		{this.state.letters.map(letter =>
		<li key={letter} onClick={()=> this.handleClick(letter)}>
			{letter}
		</li>
		)}
	</ul>
</div>
)
}
}


二、傳遞自定義屬性給點(diǎn)擊事件文件

通過定義屬性 ?letter? 值,然后在通過 ?e.target.dataset ?來獲取值。代碼如下:

const A = 65 
 
class Alphabet extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
    this.state = {
      justClicked: null,
      letters: Array.from({length: 26}, (_, i) => String.fromCharCode(A + i))
    };
  }
 
  handleClick(e) {
    this.setState({
      justClicked: e.target.dataset.letter
    });
  }
 
  render() {
    return (
      <div>
        Just clicked: {this.state.justClicked}
        <ul>
          {this.state.letters.map(letter =>
            <li key={letter} data-letter={letter} onClick={this.handleClick}>
              {letter}
            </li>
          )}
        </ul>
      </div>
    )
  }
}


總結(jié):

以上就是有關(guān)于“react點(diǎn)擊事件怎么實(shí)現(xiàn)?代碼分享!”的內(nèi)容,當(dāng)然如果你有更好的方法也可以和大家一起分享學(xué)習(xí)。更多關(guān)于 react 框架內(nèi)容的知識點(diǎn),我們都可以在 React 教程 中進(jìn)行學(xué)習(xí)和了解。


0 人點(diǎn)贊