javascript - 无法通过 id 找到 React.Component

标签 javascript html reactjs

我有一个 React.Component,其中 render() 是这样声明的:

render(){
    return <div>
        <button id="butt" onClick={()=> $("#noti").change("test") }>click me</button>
        <Notification id="noti" onMounted={() => console.log("test")}/>
    </div>
}

这是我的 Notification 类:

class Notification extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            message: "place holder",
            visible: false
        }
    }

    show(message, duration){
        console.log("show")
        this.setState({visible: true, message})
        setTimeout(() => {
            this.setState({visible: false})
        }, duration)
    }

    change(message){
        this.setState({message})
    }

    render() {
      const {visible, message} = this.state
      return <div>
          {visible ? message : ""}
      </div>
    }
  }

正如类名所暗示的,我正在尝试创建一个带有消息的简单通知。我只想通过调用 noti.show(message, duration) 来显示通知。

但是,当我尝试通过执行 window.noti$("#noti")document 来查找 noti 时.findElementById("noti"),都给我undefined,而noti显示正常。我可以使用代码找到 butt 来找到 noti

我应该如何找到noti?我是前端新手,所以请更具体地解释一下。

最佳答案

在 Reactjs 中使用 JQuery 库不是一个好主意。相反,你可以找到一个合适的 react 库来进行通知或其他任何事情。

此外,在 React 中,我们使用 ref 来访问 DOM 节点。 像这样:

    constructor(props) {
        super(props);
        this.noti = React.createRef();
    }

    ...

    <Notification ref={this.noti} onMounted={() => console.log("test")}/>

更多信息:https://reactjs.org/docs/refs-and-the-dom.html

关于javascript - 无法通过 id 找到 React.Component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58851837/

相关文章:

javascript - 如何在选择除一个链接之外的所有链接时运行脚本

html - 为什么 table th 字体垂直居中在 css 中不起作用?

javascript - 无法访问文件上传的路径键

javascript - 在 React/Redux 中模块化代码

reactjs - 在 redux 工具包中使用 dispatch 发送多个 Action

android - 有没有办法改变 <Tabs> 中 <Tab> 标签的宽度?

javascript - 获取编辑后的输入文本框的内容

javascript - 翻译单页应用程序

javascript - SweetAlert2 - 如果有一个按钮,模式一打开它就会突出显示

html - 悬停不在 css 菜单 active li 类上工作?对别人有用吗?