我是新来的反应者,尝试获取输入中提交的信息并将其作为输出返回到导航组件所在的地方时遇到问题。我希望输出返回到Content组件,但是我很难尝试弄清楚该怎么做。尝试将其作为道具返回时会返回未定义状态。我已经阅读了文档,并试图在视频中找到答案,但似乎没有任何方法可以解决问题。谁能指出我正确的方向?
private static object messageLock = new object();
public static void writeMessage(string message, string message2)
{
lock (messageLock)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write(message);
Console.ResetColor();
Console.Write(" " + message2 + " ");
}
}
答案 0 :(得分:0)
您可以创建一个简单的输入组件,但值和事件处理程序来自父级,作为道具 看这个例子
import React, { useState } from 'react'
import Input from './Input'
const App = () => {
const [InputOneValue, setInputOnValue] = useState("")
const [InputTwoValue, setInputTwoValue] = useState("")
const InputOneChangeHandler = (value) => {
setInputOneValue(value)
}
const InputTwoChangeHandle = (value) => {
setInputTwoValue(value)
}
const onSubmitHanlder = () {
// InputOneValue
// InputTwoValue
}
return (
<form onSubmit={submitHandler}>
<Input value={InputOneValue} changeHandler={InputOneChangeHandler}
<Input value={InputTwoValue} changeHandler={InputTwoChangeHandler}
</form>
)
}
export default App
这就是您的输入组件
const Input = (props) => {
return <input value={props.value} onChange={props.changeHandler} />
}
export default Input
答案 1 :(得分:0)
您不需要编写句柄更改,也不需要将userInput存储在Nav中。直接存储在App.js中。因此,在Nav中使用this.handleChange
而不是this.props.changed
可以帮助您将userInput存储在App中,然后可以将数据作为props传递。
// this is the root component
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
userInput: ""
}
}
handleChange = (e) => {
this.setState({
userInput: e.target.value
})
}
render() {
const { userInput } = this.state
return (
<div className="recipes">
<Nav userInput={this.state.userInput} />
<Content userInput={this.state.userInput} changed={this.handleChange} />
</div>
)
}
}
class Nav extends React.Component {
render() {
return (
<nav className="nav">
<h1 className="title" >Nourish</h1>
<h2 className="title" >{this.state.userInput}</h2>
<input type="text" className="input" onChange={this.props.changed} />
</nav>
)
}
}
// this is where I want to output the value to
const Content = (props) => {
console.log(props.userInput)
return (
<h2 className="main"> {props.userInput} </h2>
)
}