React JS可用this.props,Reagent的:reagent-render如何获取Props?
在Reagent中获取Props的方法
嘿,我来帮你捋清楚Reagent里怎么获取props——和React JavaScript版本的this.props确实不一样,但其实更简洁哦!
核心逻辑:Props作为组件函数的参数传入
在Reagent的:reagent-render回调(或者你定义的函数式组件)里,props会直接作为函数的参数传递进来,不需要用this来访问。
举个基础例子:
(defn my-chart-component [props] ;; 直接从props里提取需要的属性 (let [chart-data (:data props) chart-config (:config props)] ;; 这里就可以用chart-data和chart-config来实现Chart.js第14行的逻辑啦 [:div ;; 比如初始化Chart.js的代码,就可以用这些变量 ]))
更简洁的写法:解构赋值
如果你想少写点代码,可以直接在函数参数里解构props,把需要的属性直接提取出来:
(defn my-chart-component [{:keys [data config]}] ;; 这里直接用data和config变量就行,不用再写(:data props) [:div ;; 比如对应Chart.js第14行的操作,比如把data传给图表组件 [:> Chart {:data data :options config}] ])
类组件场景(不推荐,但也支持)
要是你用的是Reagent的类组件(create-class方式),:reagent-render的回调函数第一个参数同样是props:
(def my-chart-component (reagent/create-class {:reagent-render (fn [props] ;; 这里直接用props获取属性 [:div (:title props)])}))
举个对应React JS的对比例子:
假设你React JS里的代码是这样的(对应Chart.js第14行):
render() { return <Chart data={this.props.data} options={this.props.options} />; }
那Reagent里对应的写法就是:
(defn my-chart-component [{:keys [data options]}] [:> Chart {:data data :options options}])
内容的提问来源于stack exchange,提问作者user9240263
相关产品推荐
相关产品推荐

