首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >React-js无法识别AmbientLightSensor

React-js无法识别AmbientLightSensor
EN

Stack Overflow用户
提问于 2019-03-25 08:35:27
回答 3查看 348关注 0票数 0

我正在尝试将传感器的API与react一起使用,但我看不到它能够工作。

它给我一个错误,告诉我AmbientLightSensor (in my case this sensor)是未定义的

如果我在react ( more exactly with an extension from VSCode "live server" )之外运行这个脚本,它可以很好地工作,( just a html with some JS code in it )。这很酷,但在这种情况下,至少我想在react中运行这个脚本,但它不让我这样做。

到目前为止我已经尝试过了:

  • 在react中将此代码作为componentDidMount调用的类方法运行,(简单地说,我已经将JS代码放在其中^^ )
  • 使用标签运行此代码,希望react不是真正使用我所知道的JS,并且可能在html中运行它会改变这一点……不,它没有起作用,所以在这一点上,我甚至不确定要检查什么才能使它工作,

以下是我的代码,我尝试运行的js代码位于Did挂载组件内

class App extends Component {
    constructor(props) {
        super(props);
    }
    componentDidMount() {
        const details = document.getElementById("details");

        // Feature detection
        if (window.AmbientLightSensor) {
            try {
                const sensor = new AmbientLightSensor();
                // Detect changes in the light
                sensor.onreading = () => {
                    details.innerHTML = sensor.illuminance;

                    // Read the light levels in lux
                    // < 50 is dark room
                    if (sensor.illuminance < 50) {
                        document.body.className = "darkLight";
                    } else {
                        document.body.className = "brightLight";
                    }
                };

                // Has an error occured?
                sensor.onerror = event =>
                    (document.getElementById("details").innerHTML =
                        event.error.message);
                sensor.start();
            } catch (err) {
                details.innerHTML = err.message;
            }
        } else {
            details.innerHTML =
                "It looks like your browser doesnt support this feature";
        }
      }

    render() {
        return (
            <div className="app">
                <h1>Ambient Light Sensor</h1>
                <p>Current Light Levels</p>
                <div id="details"></div>
            </div>
        );
    }
}

这也是正在运行的html

<head>
    <meta charset="UTF-8" />
    <title>Ambient Light Sensor</title>
</head>

<body class="brightLight">
    <h1>Ambient Light Sensor</h1>
    <p>Current Light Levels</p>
    <div id="details"></div>
</body>
<script>
    const details = document.getElementById("details");

    // Feature detection
    if (window.AmbientLightSensor) {
        try {
            const sensor = new AmbientLightSensor();
            // Detect changes in the light
            sensor.onreading = () => {
                details.innerHTML = sensor.illuminance;

                // Read the light levels in lux
                // < 50 is dark room
                if (sensor.illuminance < 50) {
                    document.body.className = "darkLight";
                } else {
                    document.body.className = "brightLight";
                }
            };

            // Has an error occured?
            sensor.onerror = event =>
                (document.getElementById("details").innerHTML =
                    event.error.message);
            sensor.start();
        } catch (err) {
            details.innerHTML = err.message;
        }
    } else {
        details.innerHTML =
            "It looks like your browser doesnt support this feature";
    }
</script>

</html>```

PS* for this to work you need to run this on a https server
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-03-25 09:18:09

React不是这样工作的.

我建议在这里查看dangerouslySetInnerHTML链接:https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml

这里有createRef链接:https://reactjs.org/docs/refs-and-the-dom.html#creating-refs

下面是一个利用两者的简单示例,让您有更好的想法:

import React from 'react';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.detailsRef = React.createRef();
  }

  createMarkup() {
    return { __html: 'whatever you want...' };
  }

  componentDidMount() {
    console.log(this.detailsRef.current.innerHTML);
  }

  render() {
    return (
      <div className="app">
        <h1>Ambient Light Sensor</h1>
        <p>Current Light Levels</p>
        <div
          ref={this.detailsRef}
          dangerouslySetInnerHTML={this.createMarkup()}
        />
      </div>
    );
  }
}

export default App;

尝试一下,阅读官方文档中的链接,以适应您的特定用例……

票数 1
EN

Stack Overflow用户

发布于 2019-03-25 09:50:28

以前从未使用过AmbientLightSensor应用程序接口,但是:尝试如下所示:

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            details: ''
        };
    }
    componentDidMount() {
        if (window.AmbientLightSensor) {
            try {
                const sensor = new AmbientLightSensor();

                sensor.onreading = () => {
                    this.setState({ details: sensor.illuminance });

                    if (sensor.illuminance < 50) {
                        document.body.className = 'darkLight';
                    } else {
                        document.body.className = 'brightLight';
                    }
                };
                sensor.onerror = event =>
                    this.setState({ details: event.error.message });

                sensor.start();
            } catch (err) {
                this.setState({ details: err.message });
            }
        } else {
            this.setState({
                details:
                    'It looks like your browser doesnt support this feature'
            });
        }
    }

    render() {
        return (
            <div className="app">
                <h1>Ambient Light Sensor</h1>
                <p>Current Light Levels</p>
                <div id="details">{this.state.details}</div>
            </div>
        );
    }
}
票数 1
EN

Stack Overflow用户

发布于 2019-03-26 17:11:28

好了,我明白了:D我发现的唯一有效的方法是发送一个JavaScript文件并运行它is by declaring it in the index.html file inside the public folder (如果你用create react应用制作了这个应用)

Normally react servers you this file and it adds it's components over it.

在react类中运行脚本不会这样做的原因(据我所知)是因为react实际上并没有在那里运行JavaScript,而是一种基于JavaScript ES6之上的语言。

虽然这意味着你可能习惯的大多数功能都可以在其中工作,但也有例外,主要是新功能(如传感器的API,它是相当新的)。

这在未来可能不是问题,但就目前而言,我猜这是一种方法。

编辑*和@SakoBu的答案被证明是安全的方法

(#改变我的想法:3 )

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55329956

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档