使用匿名函数
自 v1.2.9 开始支持 注意:在各小程序端,使用匿名函数,尤其是在 循环中 使用匿名函数,比**使用
bind进行事件传参占用更大的内存,速度也会更慢。**
除了 bind 之外,事件参数也可以使用匿名函数进行传参。直接写匿名函数不会打乱原有监听函数的参数顺序:
class Popper extends Component {constructor () {super(...arguments)this.state = { name: 'Hello world!' }}render () {const name = 'test'return (<Button onClick={(e) => {e.stopPropagation()this.setState({name})}}>{this.state.name}</Button>)}}
注意: 使用通过
usingComponents的第三方组件不支持匿名函数
柯里化
自 v1.3.0-beta.1 开始支持 在各小程序端,使用柯里化 Taro 会在编译后多生成一个匿名函数。
除了 bind 和匿名函数之外,事件参数也可以使用柯里化传参。
class Title extends Component{handleClick = (index) => (e) => {e.stopPropagation()this.setState({currentIndex: index})}render() {const { currentIndex } = this.props;return ({/* 调用 `this.handleClick(currentIndex)` 会返回一个函数,这个函数可以访问到 `currentIndex` 同时也能满足 `onClick` 的签名 */}<View onClick={this.handleClick(currentIndex)}></View>)}}
注意: 使用通过
usingComponents的第三方组件不支持匿名函数
函数式组件
在函数式组件中,事件传参可以传入事件的引用也可以传入匿名函数,以下是函数式组件配合 useCallback 的一个例子:
const App = () => {const [c1, setC1] = useState(0);const [c2, setC2] = useState(0);const [c3, setC3] = useState(0);const increment = c => c + 1// 只有 useCallback 对应的 c1 或 c2 的值改变时,才会返回新的函数const increment1 = useCallback(() => setC1(increment), [c1]);const increment2 = useCallback(() => setC2(increment), [c2]);return (<View><Text> Counter 1 is {c1} </Text><Text> Counter 2 is {c2} </Text><Text> Counter 3 is {c3} </Text><View><Button onClick={increment1}>Increment Counter 1</Button><Button onClick={increment2}>Increment Counter 2</Button><Button onClick={() => setC3(increment)}>Increment Counter 3</Button></View></View>)}
