gpt4 book ai didi

javascript - 将 createClass 更改为 Component

转载 作者:行者123 更新时间:2023-11-28 14:41:13 25 4
gpt4 key购买 nike

我是 React 新手,对于这个非常基本的问题感到抱歉。我在 Google 上搜索并尝试了其他 StackOverflow 帖子,但没有任何效果。我正在尝试创建一个带有验证的表单,我发现了这个示例:

import t from 'tcomb-form'

const FormSchema = t.struct({
name: t.String, // a required string
age: t.maybe(t.Number), // an optional number
rememberMe: t.Boolean // a boolean
})

const App = React.createClass({

onSubmit(evt) {
evt.preventDefault()
const value = this.refs.form.getValue()
if (value) {
console.log(value)
}
},

render() {
return (
<form onSubmit={this.onSubmit}>
<t.form.Form ref="form" type={FormSchema} />
<div className="form-group">
<button type="submit" className="btn btn-primary">Save</button>
</div>
</form>
)
}

})

但是我想将其转换为正常方式:

export class GiveFeedback extends Component {...}

这是我的尝试:

从“react”导入 React, { Component }从“tcomb-form”导入 t

export class GiveFeedback extends Component {

const FormSchema = t.struct({
name: t.String, // a required string
age: t.maybe(t.Number), // an optional number
rememberMe: t.Boolean // a boolean
})

onSubmit(evt) {
evt.preventDefault()
const value = this.refs.form.getValue()
if (value) {
console.log(value)
}
}

render() {
return (
<form onSubmit={this.onSubmit}>
<t.form.Form ref="form" type={FormSchema} />
<div className="form-group">
<button type="submit" className="btn btn-primary">Save</button>
</div>
</form>
)
}

}

export default GiveFeedback

但是,当我运行代码时,出现此错误:

Unexpected token (7:10)

5 | export class GiveFeedback extends Component { 6 | 7 | const FormSchema = t.struct({ | ^ 8 | name: t.String, // a required string 9 | age: t.maybe(t.Number), // an optional number 10 | rememberMe: t.Boolean // a boolean

我希望有人能帮忙。

非常感谢

最佳答案

一切都很好,你只需将 const 放入类中即可,因此它无效

删除您的代码并将其放在类之外

 const FormSchema = t.struct({
name: t.String, // a required string
age: t.maybe(t.Number), // an optional number
rememberMe: t.Boolean // a boolean
})

export class GiveFeedback extends Component {
......
}

或者你也可以将 const 放在 render() 函数中

信息:在React组件中定义的任何自定义方法都需要引用this,如果没有这个,您将无法使用setState和其他类方法

有很多方法可以将其绑定(bind)到方法

1.

export class GiveFeedback extends Component {
constructor(){
super();
this.yourMethod = this.yourMethod.bind(this);
}
yourMethod(){
//now you get this.state and any other object of class
}
}

2.

export class GiveFeedback extends Component {
constructor(){
super();
}

yourMethod(){
//now you get this.state and any other object of class
}

render(){
//bind runtime
return(<Text onPress={this.yourMethod.bind(this)}>click</Text>)
}
}

3.

export class GiveFeedback extends Component {
constructor(){
super();
}

yourMethod = ()=>{
// this style is es6 so no need to bind and scope remain same
//now you get this.state and any other object of class
}
}

关于javascript - 将 createClass 更改为 Component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47906356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com