Riot.js 未定义的值

Riot.js 未定义的值,riot.js,riot,Riot.js,Riot,有人能告诉我为什么我的代码不起作用吗 我得到“this.username未定义”,我真的不明白为什么 代码如下: riot.tag2('test', '<input type="text" name="username" placeholder="username" oninput={validate} value="" /> <h4>{username_valid}</h4>', '', '', function(opts) { this.valid

有人能告诉我为什么我的代码不起作用吗

我得到“this.username未定义”,我真的不明白为什么

代码如下:

riot.tag2('test', '<input type="text" name="username" placeholder="username" oninput={validate} value="" /> <h4>{username_valid}</h4>', '', '', function(opts) {
    this.validate = function(e) {
        this.username_valid = (this.username.value.length > 3) ? 'Valid' : 'Invalid'
    };
});
riot.tag2('test','{username\u valid}','',函数(opts){
this.validate=函数(e){
this.username\u valid=(this.username.value.length>3)?“有效”:“无效”
};
});

感谢您的帮助。

仅仅因为它很难阅读,我希望您不是在使用riot API编写组件。我把它转录成一个标签,这样我们可以看得更清楚:

<test>

  <input
    type="text"
    name="username"
    placeholder="username"
    oninput={validate}
    value=""/>

  <h4>{username_valid}</h4>

  <script>

    this.validate = function(e) {
        this.username_valid = (this.username.value.length > 3) ? 'Valid' : 'Invalid'
    }

  </script>
</test>

{username\u valid}
this.validate=函数(e){
this.username\u valid=(this.username.value.length>3)?“有效”:“无效”
}
您正在尝试从输入元素获取用户名
标记中的此
指的是脚本的范围,而不是DOM元素。有几种方法可以获得输入值

  • ref='username'
    添加到
    标记。
    然后使用
    this.refs.username.value
    从ref获取值

  • validate
    函数中,使用
    e.target.value
    从oninput事件获取元素

  • 使用
    this.root.querySelectorAll('input')[0].value
    进行作用域DOM查询


  • 仅仅因为它很难阅读,我希望您不是在使用RiotAPI编写组件。我把它转录成一个标签,这样我们可以看得更清楚:

    <test>
    
      <input
        type="text"
        name="username"
        placeholder="username"
        oninput={validate}
        value=""/>
    
      <h4>{username_valid}</h4>
    
      <script>
    
        this.validate = function(e) {
            this.username_valid = (this.username.value.length > 3) ? 'Valid' : 'Invalid'
        }
    
      </script>
    </test>
    
    
    {username\u valid}
    this.validate=函数(e){
    this.username\u valid=(this.username.value.length>3)?“有效”:“无效”
    }
    
    您正在尝试从输入元素获取用户名
    标记中的此
    指的是脚本的范围,而不是DOM元素。有几种方法可以获得输入值

  • ref='username'
    添加到
    标记。
    然后使用
    this.refs.username.value
    从ref获取值

  • validate
    函数中,使用
    e.target.value
    从oninput事件获取元素

  • 使用
    this.root.querySelectorAll('input')[0].value
    进行作用域DOM查询


  • 你用的是哪个版本?如果使用v3,则需要使用refs来引用变量。因此,在输入中,应该有ref=“username”,在方法中应该有this.refs.username.value。你用的是哪个版本?如果使用v3,则需要使用refs来引用变量。因此,在输入中,应该有ref=“username”,在方法中应该有this.refs.username.value。