React中的Annyang - 最佳实践

3
我希望将语音识别集成到我的React项目中,我可能会将每个可以通过语音识别控制的功能分离成服务,但目前我非常困惑如何处理这个问题。
我能够将Annyang放置在我的索引中并运行以下代码:
const annyang = require('annyang');
if (annyang) {
// Let's define a command.
annyang.debug();
var commands = {
  'hello world': function() { alert('Hello'); }
};

// Add our commands to annyang
annyang.addCommands(commands);

annyang.addCallback('soundstart', function() {
  console.log('sound detected');
});

annyang.addCallback('result', function() {
  console.log('sound stopped');
});
// Start listening.
annyang.start();
}

但是我真的很困惑这段代码如何与我已经拥有的组件交互?我对React是新手,希望了解像这样的最佳实践。

我在考虑将此代码运行在自己的文件中,并导出模块并在我的组件中要求它,这是一个好的实践还是我漏掉了什么?

如果我表述不清,请让我知道,我会尽力解释。

2个回答

4
这取决于您的目标是什么。
一个好的实践是将所有Annyang命令放置在顶层组件中(例如<App/>),并在执行语音命令时设置状态(或调度操作)。这是一个非常基本的示例,没有任何flux实现或多个组件:

class App extends React.Component {
  constructor() {
    super();
    this.state = { hello: false };
  }
  componentDidMount() {
    if (annyang) {
      // Let's define a command.
      var commands = {
        'hello': () => this.setState({ hello: true })
      };

      // Add our commands to annyang
      annyang.addCommands(commands);

      // Start listening.
      annyang.start();
    }
  }
  render() {
    return this.state.hello ? <SaidHello /> : <Welcome />;
  }

}

class Welcome extends React.Component {
  render() {
    return <div>Say "hello"!</div>;
  }
}

class SaidHello extends React.Component {
  render() {
    return <div>Well, hello! How are you?</div>;
  }
}

ReactDOM.render(<App/>, document.getElementById('View'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/annyang/2.6.0/annyang.min.js"></script>

<div id="View"></div>

请记得在浏览器中允许麦克风访问,否则它将无法工作。如果这个例子在 StackOverflow 上不起作用,请在 JSBin 上查看


我相信这个例子适合我将要使用的目的,这个def给了我一些可以使用的东西。谢谢你的时间 :) - ExohJosh

-1

如果你想使用这个库

useEffect(() => {
if (annyang) {
var commands = {
 "Hello": function,
 "Bye": function,
 "Let's have ours": function,
 "Turn on the nursery": function,
 "Who are you": function,
 "What can you do": function,
 "What are you written on": function,
 "Come on fresh": function,
"Raspberry Lada": function
 "The heat has gone": function
"Open": () => function(true),
"Close": () => function(false)
}

1
你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心找到有关如何编写良好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接