我有一个简单的代码,试图使用Scanner scanner=new Scanner(System.in);
System.out.println("Enter test 1 value");
// initial value is created and passed in to test method here
double test1 = Double.parseDouble(scanner.nextLine());
// here we grab the return value of the test method
double value1 = test(test1);
System.out.println("Enter test 2 value");
// initial value is created and passed in to tests method here
double test2 = Double.parseDouble(scanner.nextLine());
// here we grab the return value of the tests method.
double value2 = tests(test2);
// pass in the value returned from both methods (ensuring we have the latest user input) to display
display(value1, value2);
替换旧内容,并使用新内容创建新元素。
例如
replace prototype
class App extends React.Component {
constructor() {
super();
this.state = {
name: 'bold'
};
}
replace = () =>{
let oldState = this.state.name;
oldState = oldState.replace(/bold/i, React.createElement('b',{ children: 'withBold'}) )
console.log(oldState)
this.setState({ name: oldState})
}
render() {
return (
<div>
<button onClick={this.replace}>Click</button><br />
{this.state.name}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('code'));
我已经尝试<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='code'></div>
我得到了document.createElement
我的代码有什么问题?
答案 0 :(得分:1)
String.prototype.replace
期望替换值是字符串或函数。您正在传递一个对象(React.createElement(...)
)。
您的问题在这里:
oldState = oldState.replace(
/bold/i,
// The following must be a string, but you are passing in an object:
React.createElement('b',{ children: 'withBold'})
);
有很多方法可以解决此问题。 就个人而言,对于这样一个简单的案例,我会写:
this.setState(prevState => ({
name: prevState.name.toLowerCase() === 'bold'
? <b>withBold</b>
: prevState.name
});