【问题标题】:How to get element from another javascript如何从另一个javascript获取元素
【发布时间】:2018-12-10 22:22:40
【问题描述】:

首先,我想动态标题标签。 每个页面的<h2> Something</h2> 都会更改标题选项卡 所以我尝试将<h2 id="name">something</h2> 制作为一个单独的html 页面。每个不同的javascript页面都有自己的<h2> 我尝试像这样使用var something =document.getElementById("name") 然后document.title=something。 但是这个主文件无法获取外部文件中的元素。

无论如何我可以制作动态标题标签吗?

没有 jquery。

【问题讨论】:

  • 你能显示一些代码吗?
  • 如果你使用 ReactJS,根据这篇文章的标签,你不应该使用document.getElementById。此外,如果您有多个元素使用相同的 id,那也不起作用。请添加一些代码以帮助澄清。当您说“选项卡”时,我们不知道您是指浏览器选项卡、应用程序选项卡还是其他内容。
  • 我的意思是浏览器选项卡,我正在使用 ReactJS
  • 在 index.html 中创建了 <body> 并且在其中每个 js 代码都在这里运行。我制作了 App.js,它导入了每一个 js 页面。这是路由的事情。我的每个 js 页面都带有const NameofFile =() =>( ......); export default NameOfFile
  • 如果你使用 react,请使用 <h2>{this.state.someValue}</h2> 而不是 <h2 id="some-id"></h2> + document.getElementById("some-id")

标签: javascript html reactjs call element


【解决方案1】:

使用 ReactJS

您可以仅为标题创建一个组件。让该组件接受一个名为“title”的道具,然后显示该标题。

标题组件:您的标题组件可以是一个功能组件

import React from 'react'; 

export default (props) => {
  return (
    <div className="your class names for this title">
      <h2>{this.props.title}</h2>
    </div>
  )
}

这是非常好的功能组件语法。只需将文件另存为“Title.js”。你可以像这样在你的父组件中导入它:

import Title from "./path/of/Title/Title"; 

这样就可以了。如果你不习惯这种语法,你可以这样重写:

const Title = (props) => (
     <div className="your class names for this title">
       <h2>{this.props.title}</h2>
     </div>
);

这也是完全有效的。接下来,让我们讨论一下父组件。您的父组件就是您的页面。所以,为了这个例子,我们称这个组件为“Home”。

Home 组件:一个类组件(假设它有状态但不一定是类组件)

import React, { Component } from 'react';
//import Title component 
import Title from "./path/of/Title/Title"; //note: your component should be in a directory that has the same name as the component 

export default class Home extends Component {
  render() {
    return (
      <div>
        <Title title="insert title here" /> 
        <div>
          Rest of your home component
        </div>
      </div>
    )
  }
}

就是这样。你有一个动态的标题。现在,假设您想将一个变量传递给道具“title”,而不是总是对字符串进行硬编码。好吧,你可以更新这一行:

<Title title="insert title here" />

对此:

<Title title={nameOfVariable} />

如果该变量来自您所在的州,您可以这样做:

<Title title={this.state.nameofvariable} />

您可以随时解构您的状态并改为这样做:

render(){
  const { nameofvariable } = this.state; 
  return (
     <div>
        <Title title={nameofvariable} /> 
        <div>
          Rest of your home component
        </div>
      </div>
  );

}

这就是你所需要的。希望有帮助。祝你好运。

【讨论】:

    猜你喜欢
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-07
    • 1970-01-01
    相关资源
    最近更新 更多