我试图用寓言编写一个简单的React组件。它应该显示一个带有+和-按钮的简单计数器。它还通过道具接收消息string。
令人意外的是,代码编译了,但它抛出了一个运行时错误:
错误:对象作为React子对象无效(找到:带有键{props、上下文、推荐、更新程序、状态}的对象)。
如果您打算呈现一个子集合,请使用数组代替。
以下是代码:
module App
open Fable.Core
open Fable.Core.JsInterop
open Fable.React
open Browser
open Browser.Types
type App (message) =
inherit Component<string, int> (message) with
do
base.setInitState(0)
override this.render () =
div
[]
[
h1 [] [ str (sprintf "%s - %i" this.props this.state) ]
button [ Props.OnClick (fun _ -> this.setState (fun s _ -> s + 1)) ] [ str "+" ]
button [ Props.OnClick (fun _ -> this.setState (fun s _ -> s - 1)) ] [ str "-" ]
]
let render () =
ReactDom.render(
App "Counter",
document.getElementById "root")
render ()我的paket.lock
STORAGE: NONE
RESTRICTION: || (== netcoreapp3.1) (== netstandard2.0) (== netstandard2.1)
NUGET
remote: https://api.nuget.org/v3/index.json
Fable.Browser.Blob (1.1)
Fable.Core (>= 3.0)
FSharp.Core (>= 4.6.2)
Fable.Browser.Dom (1.1)
Fable.Browser.Blob (>= 1.1)
Fable.Browser.Event (>= 1.0)
Fable.Browser.WebStorage (>= 1.0)
Fable.Core (>= 3.0)
FSharp.Core (>= 4.6.2)
Fable.Browser.Event (1.0)
Fable.Core (>= 3.0)
FSharp.Core (>= 4.5.2)
Fable.Browser.WebStorage (1.0)
Fable.Browser.Event (>= 1.0)
Fable.Core (>= 3.0)
FSharp.Core (>= 4.5.2)
Fable.Core (3.1.5)
FSharp.Core (>= 4.7)
Fable.React (5.3.6)
Fable.Browser.Dom (>= 1.0)
Fable.Core (>= 3.0)
FSharp.Core (>= 4.7)
FSharp.Core (4.7)注意:出于各种原因,我想使用setState (而不是钩子或Elmish)。
发布于 2020-02-28 10:02:00
在render函数中,您需要使用ofType,如下所示:
let render () =
ReactDom.render(
ofType<App,_,_> "Counter" [],
document.getElementById "root")这将获得要呈现的内容,但是单击按钮时不会发生任何事情。
若要解决此问题,请将状态从int更改为object
type state = { count: int }
//..
button [ Props.OnClick (fun _ -> this.setState (fun s _ -> { s with count = s.count + 1 })) ] [ str "+" ]最后,还将您的道具更改为object。
总之,以下几点应能发挥作用:
type props = { message: string }
type state = { count: int }
type App (props) =
inherit Component<props, state> (props) with
do
base.setInitState({ count = 0 })
override this.render () =
div
[]
[
h1 [] [ str (sprintf "%s - %i" this.props.message this.state.count) ]
button [ Props.OnClick (fun _ -> this.setState (fun s _ -> { s with count = s.count + 1 })) ] [ str "+" ]
button [ Props.OnClick (fun _ -> this.setState (fun s _ -> { s with count = s.count - 1 })) ] [ str "-" ]
]
let render () =
ReactDom.render(
ofType<App,_,_> { message = "Counter" } [],
document.getElementById "root")
render ()您可以将ofType调用包装在一个方便的函数中:
let inline app props children =
ofType<App,_,_> props children
let render () =
ReactDom.render(
app { message = "Counter" } [],
document.getElementById "root")
render ()https://stackoverflow.com/questions/60416510
复制相似问题