我在 React 中有一个名为 Good Robot Bad Robot 的项目。 它看起来像这样:
(input box here)
Hello! Wanna talk to some robots?
I am good robot
I hear you are saying, ______. is that correct?
I am bad robot
I hear you are saying, ______. is that correct?`
当我在输入框中键入时,___ 会更改为用户输入。 无论用户输入什么内容,我都无法让坏机器人仅重复“BLABLABLABLA”。我知道问题出在我的函数中......我不完全确定如何编写它。 以下是 app.js 和 badrobot.js 的代码:
import React, {Component} from 'react';
import Header from './Header'
import GreetingInput from './GreetingInput'
import GoodRobot from './GoodRobot'
import BadRobot from './BadRobot'
import './App.css';
class App extends Component {
constructor(props) {
super(props)
this.state = {
greeting: '',
name:'Stephen',
robotgreeting: "______"
}
}
returnGreeting = (userSent) => {
this.setState({greeting: userSent, robotgreeting: userSent})
}
render() {
let {greeting, name, robotgreeting} = this.state
return (
<div className="App">
<div>
<Header greeting={name}/>
</div>
<div>
<GreetingInput greeting={greeting} returnGreeting={this.returnGreeting}/>
</div>
<div>
<GoodRobot greeting={robotgreeting}/>
</div>
<div>
<BadRobot greeting ={robotgreeting} />
</div>
</div>
);
}
}
export default App;
import React, {Component} from 'react';
class BadRobot extends Component {
wordManipulator = (word) => {
let newStr = this.props.greeting.split('')
let newStr2 = newStr.splice(null, word.length, 'b', 'l', 'a')
return newStr2.join("")
}
// console.log(wordManipulator(this.props.greeting))
render() {
return (
<div>
<div>
<h1>I am bad robot</h1>
<h3>I hear you are saying, {this.props.greeting}. is that correct? </h3>
</div>
</div>
);
}
}
export default BadRobot;
最佳答案
正如 @Manuel 提到的,您可能需要发送 props.greeting
变量为您的 wordManipulator
函数以呈现所需的输出。
此外,在您的 wordManipulator
中函数,这一行 newStr.splice(null, word.length, 'b', 'l', 'a')
只会返回bla
无论 props.greeting
多变的。如果我理解正确的话你想重复 bla
当你打字时。
我编辑了wordManipulator
相应地函数只映射 props.greeting
的每个字符到bla
's(可重复字符串)对应的索引。
import React, {Component} from 'react';
const BLAH = "BLAH";
class BadRobot extends Component {
wordManipulator = (word) => word.split("").map((c, i) => BLAH[(i % BLAH.length)]).join("")
render() {
return (
<div>
<div>
<h1>I am bad robot</h1>
<h3>I hear you are saying, {this.wordManipulator(this.props.greeting)}. is that correct? </h3>
</div>
</div>
);
}
}
export default BadRobot;
const greeting = "HELLO ROBOT!"
const BLAH = "BLAH";
const wordManipulator = (word) => word.split("").map((c, i) => BLAH[(i % BLAH.length)]).join("")
console.log(wordManipulator(greeting))
关于javascript - 字符串操作 jsx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58435139/