0

我设法让活动更新,使用网络片段,我很难理解。这是整个片段:

type state = {
    login: string,
    password: string
};

type action =
    | SetLogin(string)
    | SetPassword(string);


let component = ReasonReact.reducerComponent("Login");

let make = (_children) => {
    ...component,
    initialState: ()=> { login: "", password: "" },

    reducer: (action, state) =>
        switch (action) {
            | SetLogin (data) => ReasonReact.Update({...state, login: data })
            | SetPassword (data) => ReasonReact.Update({...state, password: data })
        },

    render: self =>
        <div>
            (ReasonReact.string("login"))
            <input
                value=self.state.login
                onChange={ev => self.send(SetLogin(ReactDOMRe.domElementToObj(ReactEventRe.Form.target(ev))##value))}
            />
            (ReasonReact.string("password"))
            <input
                value=self.state.password
                _type="password"
                onChange={ev => self.send(SetPassword(ReactDOMRe.domElementToObj(ReactEventRe.Form.target(ev))##value))}
            />

        </div>
};

我特别关注 onChange 行:

onChange={ev => self.send(SetLogin(ReactDOMRe.domElementToObj(ReactEventRe.Form.target(ev))##value))}

难道没有更好的方法来做到这一点吗?这似乎真的很令人费解..

4

1 回答 1

2

你正在做的事情没有错,据我所知,这是唯一的方法。我倾向于有一个辅助功能,例如:

let getValueFromEvent = event : string => (
                                            event
                                            |> ReactEventRe.Form.target
                                            |> ReactDOMRe.domElementToObj
                                          )##value;

然后它会清理一下:

<input
  value=self.state.password
  _type="password"
  onChange={event => self.send(SetPassword(getValueFromEvent(event)))}
/>
于 2018-06-12T12:15:03.490 回答