给出:
LoginUsername.re
let component = ReasonReact.statelessComponent("LoginUsername");
let make = (~value: string, _children) => {
...component,
render: (_) =>
<div>
<label htmlFor="username">{ReasonReact.string("User Name")}</label>
<input type_="text" name="username" value=value/>
</div>
};
LoginPassword.re
let component = ReasonReact.statelessComponent("LoginPassword");
let make = (~value, _children) => {
...component,
render: (_) =>
<div>
<label htmlFor="password">{ReasonReact.string("Password")}</label>
<input type_="password" name="password" value=value/>
</div>
};
Login.re
let component = ReasonReact.statelessComponent("Login");
let make = (~username: string, ~password: string, _children) => {
...component,
render: (_) =>
<div>
<h1>{ReasonReact.string("Log in")}</h1>
<div><LoginUsername key=username value=username/></div>
<div><LoginPassword key=password value=password/></div>
</div>
};
Index.re
ReactDOMRe.renderToElementWithId(<Login username="" password=""/>, "index1");
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ReasonReact Examples</title>
</head>
<body>
Component 1:
<div id="index1"></div>
<script src="../build/Index.js"></script>
</body>
</html>
为什么在我输入任何一个<input>
时都没有显示文本?
答案 0 :(得分:2)
输入永远不会更新,您需要一种机制来调用onChange,存储值并将其传递回输入中。当前值将始终为“”,因为没有任何值可以覆盖它。
您可以使用reducer组件来实现此目的:
type state = {input: string};
type action =
| UpdateInput(string);
let component = ReasonReact.reducerComponent("Input");
let make = _children => {
...component,
initialState: () => {input: ""},
reducer: (action, _state) =>
switch (action) {
| UpdateInput(input) => ReasonReact.Update({ input: input })
},
render: ({state, send}) =>
<input
onChange=(e => send(UpdateInput(e##target##value)))
value=state.input
/>,
};