你可以通过在组件中声明 事件处理 函数来响应事件:
function MyButton() {
function handleClick() {
alert('You clicked me!');
}
return (
<button onClick={handleClick}>
Click me
</button>
);
}
注意,onClick={handleClick} 的结尾没有小括号!不要 调用 事件处理函数:你只需 把函数传递给事件 即可。当用户点击按钮时 React 会调用你传递的事件处理函数。
import React from 'react'
import { View } from '@tarojs/components'
import './index.scss'
function Index() {
const user = {
name: 'Hedy Lamarr',
imageUrl: 'https://i.imgur.com/yXOvdOSs.jpg',
imageSize: 90,
isLogin: false
};
const products = [
{ title: 'Cabbage', id: 1 },
{ title: 'Garlic', id: 2 },
{ title: 'Apple', id: 3 },
];
if (user.isLogin) {
user.name = '12345'
} else {
user.name = '16789'
}
function handleClick() {
alert("are you ok")
console.log(alert("are you ok"));
}
const listItems = products.map(products =>
<li key={products.id} onClick={handleClick}>{products.title}</li>
)
return (
<View className="nutui-react-demo">
测试组件
<h1>{user.imageSize}</h1>
<p className='text-red'>{user.name}</p>
<a className='text-red' href="https://www.baidu.com">百度</a>
<img src={user.imageUrl} alt={'Photo of ' + user.name}
style={{
width: user.imageSize,
height: user.imageSize
}} />
<div>{user.imageSize > 100 ? '大于100' : '小于100'}</div>
<ul>
{listItems}
</ul>
</View>
)
}
export default Index