class PlayerControls extends React.Component {
constructor(props) {
super(props)
this.state = {
loopActive: false,
shuffleActive: false,
}
}
render() {
var shuffleClassName = this.state.toggleActive ? "player-control-icon active" : "player-control-icon"
return (
<div className="player-controls">
<FontAwesome
className="player-control-icon"
name='refresh'
onClick={this.onToggleLoop}
spin={this.state.loopActive}
/>
<FontAwesome
className={shuffleClassName}
name='random'
onClick={this.onToggleShuffle}
/>
</div>
);
}
onToggleLoop(event) {
// "this is undefined??" <--- here
this.setState({loopActive: !this.state.loopActive})
this.props.onToggleLoop()
}
我想loopActive
在切换时更新状态,但this
在处理程序中未定义对象。根据教程文档,我this
应该引用该组件。我想念什么吗?
ES6React.Component
不会自动将方法绑定到自身。您需要自己将它们绑定constructor
。像这样:
constructor (props){
super(props);
this.state = {
loopActive: false,
shuffleActive: false,
};
this.onToggleLoop = this.onToggleLoop.bind(this);
}
有两种方法。
一种是添加
this.onToggleLoop = this.onToggleLoop.bind(this);
构造函数。
另一个是箭头功能
onToggleLoop = (event) => {...}
。
然后是onClick={this.onToggleLoop.bind(this)}
。
这样编写函数:
onToggleLoop = (event) => {
this.setState({loopActive: !this.state.loopActive})
this.props.onToggleLoop()
}
关键字的绑定,外部和内部的胖箭头功能相同。这与用function声明的函数不同,后者可以在调用时将其绑定到另一个对象。维护this绑定对于诸如映射这样的操作非常方便:this.items.map(x => this.doSomethingWith(x))。
我在render函数中遇到了类似的绑定,并最终通过this
以下方式传递的上下文:
{someList.map(function(listItem) {
// your code
}, this)}
我也用过:
{someList.map((listItem, index) =>
<div onClick={this.someFunction.bind(this, listItem)} />
)}
您应该注意到,这this
取决于调用函数的方式,即:当将函数作为this
对象的方法调用时,将其设置为调用该方法的对象。
this
可在JSX上下文中作为组件对象访问,因此可以将所需的方法作为this
方法内联调用。
如果您只是传递对函数/方法的引用,似乎react会将其作为独立函数调用。
onClick={this.onToggleLoop} // Here you just passing reference, React will invoke it as independent function and this will be undefined
onClick={()=>this.onToggleLoop()} // Here you invoking your desired function as method of this, and this in that function will be set to object from that function is called ie: your component object
如果您正在使用babel,则可以使用ES7绑定运算符https://babeljs.io/docs/en/babel-plugin-transform-function-bind#auto-self-binding来绑定'this'
export default class SignupPage extends React.Component {
constructor(props) {
super(props);
}
handleSubmit(e) {
e.preventDefault();
const data = {
email: this.refs.email.value,
}
}
render() {
const {errors} = this.props;
return (
<div className="view-container registrations new">
<main>
<form id="sign_up_form" onSubmit={::this.handleSubmit}>
<div className="field">
<input ref="email" id="user_email" type="email" placeholder="Email" />
</div>
<div className="field">
<input ref="password" id="user_password" type="new-password" placeholder="Password" />
</div>
<button type="submit">Sign up</button>
</form>
</main>
</div>
)
}
}
如果您在生命周期方法(例如componentDidMount ...)中调用创建的方法,则只能使用this.onToggleLoop = this.onToogleLoop.bind(this)
和箭头功能onToggleLoop = (event) => {...}
。
在构造函数中声明函数的常规方法将不起作用,因为生命周期方法被更早地调用。
就我而言,这就是解决方案 =()=> {}
methodName = (params) => {
//your code here with this.something
}
在我的情况下,对于使用forwardRef接收到ref的无状态组件,我必须按照这里所说的去做:https: //itnext.io/reusing-the-ref-from-forwardref-with-react-hooks-4ce9df693dd
由此(onClick不能访问与“ this”相对应的内容)
const Com = forwardRef((props, ref) => {
return <input ref={ref} onClick={() => {console.log(ref.current} } />
})
对此(有效)
const useCombinedRefs = (...refs) => {
const targetRef = React.useRef()
useEffect(() => {
refs.forEach(ref => {
if (!ref) return
if (typeof ref === 'function') ref(targetRef.current)
else ref.current = targetRef.current
})
}, [refs])
return targetRef
}
const Com = forwardRef((props, ref) => {
const innerRef = useRef()
const combinedRef = useCombinedRefs(ref, innerRef)
return <input ref={combinedRef } onClick={() => {console.log(combinedRef .current} } />
})
您可以重写如何从render()方法调用onToggleLoop方法。
render() {
var shuffleClassName = this.state.toggleActive ? "player-control-icon active" : "player-control-icon"
return (
<div className="player-controls">
<FontAwesome
className="player-control-icon"
name='refresh'
onClick={(event) => this.onToggleLoop(event)}
spin={this.state.loopActive}
/>
</div>
);
}
该阵营的文档在属性拨打电话,从表情到功能显示了这种模式。
文章标签:javascript , reactjs , this
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!
评论已关闭!