理由如何更好地处理事件?

时间:2018-06-09 20:06:05

标签: reason reason-react

我设法让事件更新,使用网络片段,我很难理解。以下是整个代码段:

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))}

难道没有更好的方法吗?这看起来真的很复杂......

1 个答案:

答案 0 :(得分: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)))}
/>